retire your data center - 1105 mediapdf.1105media.com/vsmmag/2009/vsm_902dg.pdfretire your data...

44
PLUS Use Lambda Expressions for Abstract Delegates Use Iterators in VB FEBRUARY 2009 Vol. 19, No. 2 RETIRE YOUR DATA CENTER Use Azure Services to Maximize Availability, Reliability, and Scalability. VisualStudioMagazine.com Where Have All the Coders Gone? ENTERPRISE SOLUTIONS FOR .NET DEVELOPMENT

Upload: buianh

Post on 31-Mar-2018

221 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

PLUS

Use Lambda Expressionsfor Abstract Delegates

Use Iterators in VB

FEB

RU

AR

Y 2

00

9 bull

Vol

19

N

o 2

RETIRE YOURDATA CENTERUse Azure Services to Maximize AvailabilityReliability and Scalability

VisualStudioMagazinecom

Where Have All the Coders Gone

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

0209vsmC1v2 12209 131 PM Page 1

BeTheDataGuru

Visual Studio WPFSilverlight SharePoint SQL Server PowerShellJava COM

Project5 121108 442 PM Page 1

Data visualization for every need every platform

Our most popular product Chart FX providescharts gauges and maps with additional verticalvisualization functionality for business intelligence(OLAP) geographic data financial technicalanalysis and statistical studies andformulas Recognized as the innovatorand leader of the charting componentcategory for the past 15 years Chart FXdelivers incomparable gallery optionsaesthetics and data analysis features

Grid FX was specifically designed for visual studiodevelopers to take advantage of a powerfuldesign-time experience integrated Chart FXfunctionality right in the box and AJAX toprovide robust run-time functionality in ASPnetapplications The dynamic aesthetic features for data presentation and analysis allow simpleadaptation to an existing application or to specificcorporate branding guidelines

PowerGadgets puts powerful IT monitoring on your desktop and in your data sidebarIT professionals can now create gadgetsthat consume data from WMI ExchangeSQL Server and even the Windows RegistryPowerGadgets does not require anydevelopment environments servers orbrowsers to run real-time gadget componentssuch as charts gauges and maps

To master the art of data visualization you must seek out the leader For almost two decadesSoftware FX has risen above all others by bringing top-of-the-line data visualization tools toenterprise developers working with diverse markets platforms and environments Thiswisdom has evolved into a vast body of products including a data presentation tool thatprovides a best-of-breed solution for Windows developers seeking enterprise quality andperformance as well as a professional IT monitoring solution offering incredible features forreporting and monitoring data For a world of data visualization products that can raise yourwork to a higher level depend on the source thatrsquos clearly on top

AchieveAHigherStateOfDataVisualization

Visit softwarefxcom for interactive demos and more information about our latest products

Project5 121108 443 PM Page 2

Project4 6208 1213 PM Page 1

wwwvisualstudiomagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 3

C CORNER

26 Use Lambda Expressions for Abstract DelegatesLambda expressions are nothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegateAnd more importantly what can you do about itBY BILL WAGNER

ON VB

32 Use Iterators in VB NowIterators are a crucial part of modern programmingnot least because they provide the basis for collection traversal using For Each loops Learn how to take advantage of them in your code withseveral different techniques for creating your owniterators in VB BY BILL MCCARTHY

DEPARTMENTS6 Editorrsquos Note BY PATRICK MEADER

10 Letters to the Editor

11 First LooksProduct Listings 11Review 13

39 Index of Advertisers

40 The Human FactorWhere Did All the Developers Go

BY DANIEL APPLEMAN

FEATURES

14 Retire Your Data CenterVisual Studio 2008 ASPNET and the Azure Services Platform combineto simplify local development of data-intensive Web apps and automatetheir deployment in Microsoft data centers The result You get maximizedavailability and reliability with almost limitless on-demand scalabilitywhile you pay only for resources consumed BY ROGER JENNINGS

COLUMNS

14

ldquoThe primary economic justificationfor moving data center activity intothe cloud is avoidance of capitalexpenditure for servers and associatednetworking hardware to handle peakinstead of average loadsrdquo

Roger Jennings ldquoRetire Your Data Centerrdquo p 14

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

ContentsFebruary 2009 bull VOLUME 19 bull NO 2

32

0209vsm_TOC_3-4v10 12209 133 PM Page 3

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom4

LEARN FROM THE PROSAs a developer you are constantly facing the problem of how to keep upwith all the new technologies beingreleased while still getting your jobdone You keep hearing about solutionsto your programming problems but the question is are they the rightsolutions for your particular needsYou could spend hours or even daystrying to find the answers yourself oryou could let the experts do it for youRedmond Media Group Events offers avariety of conferences and showswhere you can learn about new

technologies and what they might offer you attend in-depth workshops thatfocus on topics specific to your needs ask questions of the experts andinteract with your peers to discuss problems they face and what solutionstheyrsquove come up with Whether itrsquos Web design NET development or SQLServer programming wersquove got an event that matches your needs VisitRedmondEventscom to learn more about upcoming conferences and shows

ONLINE ARTICLES

Practical ASPNET Decoding RoutesIn his ongoing series on ASPNET Peter Vogel talks about the routingfeature included in Service Pack 1 for NET 35 and shows how to set upa site to use routes In this installment Vogel talks about the class filethat you must create to handle the conversion between the meaningfulURL provided by the user and the real path to your WebForm LOCATOR+ CODE VS0902PV1

Practical ASPNET Supporting RoutingIn this edition of Peter Vogelrsquos Practical ASPNET column he goes beyondthe basics of routing to look at some additional features The goals hereare to simplify your code and make life easier for your usersLOCATOR+ CODE VS0902PV2

ONLINE BLOGS

VSMrsquos Big IssueVisual Studio Magazinersquos Editor in Chief Patrick Meader and ManagingEditor Guy Wright have started a collaborative blog where they take alook at some of the bigger issues facing NET developers these days

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

VisualStudioMagazinecom

ContentThe blog will feature opinions and interviews with industryinsiders and pose questions designed to stimulate discussionCheck out their blog at VisualStudioMagazinecomLOCATOR+ CODE VS0901BI

ONLINE TUTORIALS

Classic VB Corner Executing DebuggablesHave you ever had one of those problems that only manifests itself in a compiled EXE that you simply canrsquotreproduce in the Classic Visual Basic IDE Or even worsethat only occurs on the clientrsquos machines and not onyours 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 RightConventional wisdom has it that version 1 of any Microsoftproduct or idea is really an alpha that version 2 is the betaand that the safe money rides on version 3 Then followingversion 3 Microsoft generally proceeds to do its best toupset the success it found in that golden release Karl EPeterson takes a trip down memory lane to one of the mostdurable version 3 products ever to come out of RedmondLOCATOR+ CODE VS0902KP2

NET NEWSLETTER SIGN-UPEvery week the NET Insight e-mail newsletter brings you up-to-date news technical information opinionsinterviews and analysis on topics and technologies such as Visual Basic NET C SQL Server and data accessASPNET wireless Web services and XML Sign up for free at VisualStudioMagazinecom

VirtualizationReviewcom1105 Media recently launcheda new Web site devoted exclusively to covering allaspects of IT virtualizationVirtualization Reviewcomhelps you harness the powerof virtualization by delivering

news and in-depth coverage of the products vendorsissues and technologies transforming IT through virtualization The site also features articles tips andtimely information about all aspects of virtualizationincluding servers storage desktops applications andmore Visit VirtualizationReviewcom now to start yourmove to a more efficient powerful virtual environment

0209vsm_TOC_3-4v10 12209 133 PM Page 4

programmersparadisecom800-445-7899

Your best source for software development tools

Prices subject to change Not responsible for typographical errors

reg

programmerscomtheimagingsource

Download a demo today

New Release

Professional EditionParadise

T79 02101A01$91999

bull NET WinForms control for VBNET and Cbull ActiveX for VB6 Delphi VBScriptHTML ASPbull File formats DOCX DOC RTF HTML XML TXTbull PDF export without additional 3rd party

tools or printer driversbull Nested tables headers amp footers text

frames bullets numbered lists multipleundoredo sections merge fields

bull Ready-to-use toolbars and dialog boxes

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

programmerscomtelerik

Telerik RadControlsby Telerik Add grid combo editing navigation and charting functionality to your AJAX and ASPNET projectsRadControls for ASPNET enhances your Web applications by adding AJAX functionality to yourASPNET projects The suite takes full advantage of the features included in Visual Studio 2005RadControls for ASPNET helps developers deliver feature-rich standards-compliant (WAI-A WCAG 10 XHTML 11) and cross-browser compatible Web applications while significantly cutting their development time RadControls for ASPNET includes RadEditor RadTabstrip RadInputRadCalendar RadUpload RadWindow RadAjaxRadGrid RadCombobox RadMenu RadSpellRadChart RadTreeview and more

Single DeveloperParadise

TB3 01101A01$64899

dtSearch Engine for Win amp NETAdd dtSearchlsquos ldquoblazing speedsrdquo (CRN Test Center) searching and file format supportbull dozens of full-text and fielded

data search optionsbull file parsersconverters for hit-highlighted

display of all popular file typesbull Spider supports dynamic and static web data

highlights hits with links images etc intactbull API supports NET C++ Java SQL and more

new NET Spider API

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo mdashInfoWorld

programmerscomdtsearch

Single ServerParadise

D29 02101A07 $94999

New64-bit

Version

programmerscomsparxsystems

New Release

Enterprise Architect 71Visualize Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensiveintegrated UML 21 modeling suite providing key benefits at each stage ofsystem development Enterprise Architect71 supports UML SysML BPMN andother open standards to analyze designtest and construct reliable well under-stood systems Additional plug-ins arealso available for Zachman FrameworkMODAF DoDAF and TOGAF and to integrate with Eclipse and Visual Studio20052008

Corporate Edition1-4 Users

Paradise SP6 0001

$19699

programmerscommultiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers a powerful IDEwith its speed depth and support forover 50 languages Enhanced searchfunctions include Perl 5 RegularExpressions and definable filtersSupports large DOSWindows UNIXbinary and Mac files File SyncIntegration for Delphi 6 7 2005C++Builder 6 BDS 2006 and RadStudio2007 VB 6 VC 6 VS 2003 amp VS2005 Includes file compare code beautifying command maps and much more

1-49 UserParadise

A30 01201A02$16199

New Release

programmerscomlead

LEADTOOLS DocumentImaging v 16by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing document clean up high-speedscanning advanced compression (CCITTG3G4 JBIG2 MRC ABC) and morebull Multi-threaded OCRICROMR

MICRBarcodes (1D2D)bull Forms recognitionprocessingbull PDF and PDFAbull Annotation (Image Mark-up)bull CC++ NET WPF - Win3264

Paradise L05 03201A01$200799

New Version

16

programmerscomnsoftware

n software Red CarpetSubscriptions by n softwaren software Red Carpettrade Subscriptions giveyou everything in one package communica-tions components for every major Internet protocol SSL and SSH security SMIMEencryption Digital Certificates Credit CardProcessing ZIP compression InstantMessaging and even e-business (EDI) transactions NET Java COM C++ Delphieverything is included together with per developer licensing free quarterly update CDsand free upgrades during the subscription termParadise

D77 09101L01 $144499

programmerscomfaircom

c-treeACEtrade Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems desktop deployments andembedded devices for over 25 years bull Complete set of APIs including ADONET LINQ

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

including Windows UNIX Linux and Mac OS X

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

Paradise F01 0131

$71199

programmerscomvmware

View PremierParadise

V55 66101A01

CALLI

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

VDI Included

New Release

programmerscommindjet

for Windows 1 User

Paradise F15 17301A02

$29999

New Release

Mindjet MindManager 8by 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

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 Yoursquoll be able to work smarter and transform your ideas into action more quickly

Infragistics NetAdvantagefor NET 2008 Volume 3by Infragistics NetAdvantagereg for NET is our comprehensivesuite of ASPNET Windows Forms WPF and Silverlight line of business controls components and tools for the NET platformNetAdvantage for NET has what you need to add no-touch AJAX to your Web site awesome power and performance to yourWindows Forms application compelling userexperiences leveraging Windows PresentationFoundation and professionally polished userinterfaces (UI) Includes Annual Subscription and Source Code

Paradise I0M 02501F01 $103399

programmerscomacresso

Acresso InstallShield 2009Professional Windowsby AcressoInstallShield Professional Edition is a powerfulyet easy-to-use solution ideal for both noviceand seasoned installation developers Whilemost homegrown installation tools are not optimized for current industry standardsInstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesmdashincluding full support forWindows Vista

Paradise I21 02201A01 $168999

programmerscominfragistics

Project17 11909 525 PM Page 1

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 2: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

BeTheDataGuru

Visual Studio WPFSilverlight SharePoint SQL Server PowerShellJava COM

Project5 121108 442 PM Page 1

Data visualization for every need every platform

Our most popular product Chart FX providescharts gauges and maps with additional verticalvisualization functionality for business intelligence(OLAP) geographic data financial technicalanalysis and statistical studies andformulas Recognized as the innovatorand leader of the charting componentcategory for the past 15 years Chart FXdelivers incomparable gallery optionsaesthetics and data analysis features

Grid FX was specifically designed for visual studiodevelopers to take advantage of a powerfuldesign-time experience integrated Chart FXfunctionality right in the box and AJAX toprovide robust run-time functionality in ASPnetapplications The dynamic aesthetic features for data presentation and analysis allow simpleadaptation to an existing application or to specificcorporate branding guidelines

PowerGadgets puts powerful IT monitoring on your desktop and in your data sidebarIT professionals can now create gadgetsthat consume data from WMI ExchangeSQL Server and even the Windows RegistryPowerGadgets does not require anydevelopment environments servers orbrowsers to run real-time gadget componentssuch as charts gauges and maps

To master the art of data visualization you must seek out the leader For almost two decadesSoftware FX has risen above all others by bringing top-of-the-line data visualization tools toenterprise developers working with diverse markets platforms and environments Thiswisdom has evolved into a vast body of products including a data presentation tool thatprovides a best-of-breed solution for Windows developers seeking enterprise quality andperformance as well as a professional IT monitoring solution offering incredible features forreporting and monitoring data For a world of data visualization products that can raise yourwork to a higher level depend on the source thatrsquos clearly on top

AchieveAHigherStateOfDataVisualization

Visit softwarefxcom for interactive demos and more information about our latest products

Project5 121108 443 PM Page 2

Project4 6208 1213 PM Page 1

wwwvisualstudiomagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 3

C CORNER

26 Use Lambda Expressions for Abstract DelegatesLambda expressions are nothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegateAnd more importantly what can you do about itBY BILL WAGNER

ON VB

32 Use Iterators in VB NowIterators are a crucial part of modern programmingnot least because they provide the basis for collection traversal using For Each loops Learn how to take advantage of them in your code withseveral different techniques for creating your owniterators in VB BY BILL MCCARTHY

DEPARTMENTS6 Editorrsquos Note BY PATRICK MEADER

10 Letters to the Editor

11 First LooksProduct Listings 11Review 13

39 Index of Advertisers

40 The Human FactorWhere Did All the Developers Go

BY DANIEL APPLEMAN

FEATURES

14 Retire Your Data CenterVisual Studio 2008 ASPNET and the Azure Services Platform combineto simplify local development of data-intensive Web apps and automatetheir deployment in Microsoft data centers The result You get maximizedavailability and reliability with almost limitless on-demand scalabilitywhile you pay only for resources consumed BY ROGER JENNINGS

COLUMNS

14

ldquoThe primary economic justificationfor moving data center activity intothe cloud is avoidance of capitalexpenditure for servers and associatednetworking hardware to handle peakinstead of average loadsrdquo

Roger Jennings ldquoRetire Your Data Centerrdquo p 14

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

ContentsFebruary 2009 bull VOLUME 19 bull NO 2

32

0209vsm_TOC_3-4v10 12209 133 PM Page 3

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom4

LEARN FROM THE PROSAs a developer you are constantly facing the problem of how to keep upwith all the new technologies beingreleased while still getting your jobdone You keep hearing about solutionsto your programming problems but the question is are they the rightsolutions for your particular needsYou could spend hours or even daystrying to find the answers yourself oryou could let the experts do it for youRedmond Media Group Events offers avariety of conferences and showswhere you can learn about new

technologies and what they might offer you attend in-depth workshops thatfocus on topics specific to your needs ask questions of the experts andinteract with your peers to discuss problems they face and what solutionstheyrsquove come up with Whether itrsquos Web design NET development or SQLServer programming wersquove got an event that matches your needs VisitRedmondEventscom to learn more about upcoming conferences and shows

ONLINE ARTICLES

Practical ASPNET Decoding RoutesIn his ongoing series on ASPNET Peter Vogel talks about the routingfeature included in Service Pack 1 for NET 35 and shows how to set upa site to use routes In this installment Vogel talks about the class filethat you must create to handle the conversion between the meaningfulURL provided by the user and the real path to your WebForm LOCATOR+ CODE VS0902PV1

Practical ASPNET Supporting RoutingIn this edition of Peter Vogelrsquos Practical ASPNET column he goes beyondthe basics of routing to look at some additional features The goals hereare to simplify your code and make life easier for your usersLOCATOR+ CODE VS0902PV2

ONLINE BLOGS

VSMrsquos Big IssueVisual Studio Magazinersquos Editor in Chief Patrick Meader and ManagingEditor Guy Wright have started a collaborative blog where they take alook at some of the bigger issues facing NET developers these days

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

VisualStudioMagazinecom

ContentThe blog will feature opinions and interviews with industryinsiders and pose questions designed to stimulate discussionCheck out their blog at VisualStudioMagazinecomLOCATOR+ CODE VS0901BI

ONLINE TUTORIALS

Classic VB Corner Executing DebuggablesHave you ever had one of those problems that only manifests itself in a compiled EXE that you simply canrsquotreproduce in the Classic Visual Basic IDE Or even worsethat only occurs on the clientrsquos machines and not onyours 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 RightConventional wisdom has it that version 1 of any Microsoftproduct or idea is really an alpha that version 2 is the betaand that the safe money rides on version 3 Then followingversion 3 Microsoft generally proceeds to do its best toupset the success it found in that golden release Karl EPeterson takes a trip down memory lane to one of the mostdurable version 3 products ever to come out of RedmondLOCATOR+ CODE VS0902KP2

NET NEWSLETTER SIGN-UPEvery week the NET Insight e-mail newsletter brings you up-to-date news technical information opinionsinterviews and analysis on topics and technologies such as Visual Basic NET C SQL Server and data accessASPNET wireless Web services and XML Sign up for free at VisualStudioMagazinecom

VirtualizationReviewcom1105 Media recently launcheda new Web site devoted exclusively to covering allaspects of IT virtualizationVirtualization Reviewcomhelps you harness the powerof virtualization by delivering

news and in-depth coverage of the products vendorsissues and technologies transforming IT through virtualization The site also features articles tips andtimely information about all aspects of virtualizationincluding servers storage desktops applications andmore Visit VirtualizationReviewcom now to start yourmove to a more efficient powerful virtual environment

0209vsm_TOC_3-4v10 12209 133 PM Page 4

programmersparadisecom800-445-7899

Your best source for software development tools

Prices subject to change Not responsible for typographical errors

reg

programmerscomtheimagingsource

Download a demo today

New Release

Professional EditionParadise

T79 02101A01$91999

bull NET WinForms control for VBNET and Cbull ActiveX for VB6 Delphi VBScriptHTML ASPbull File formats DOCX DOC RTF HTML XML TXTbull PDF export without additional 3rd party

tools or printer driversbull Nested tables headers amp footers text

frames bullets numbered lists multipleundoredo sections merge fields

bull Ready-to-use toolbars and dialog boxes

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

programmerscomtelerik

Telerik RadControlsby Telerik Add grid combo editing navigation and charting functionality to your AJAX and ASPNET projectsRadControls for ASPNET enhances your Web applications by adding AJAX functionality to yourASPNET projects The suite takes full advantage of the features included in Visual Studio 2005RadControls for ASPNET helps developers deliver feature-rich standards-compliant (WAI-A WCAG 10 XHTML 11) and cross-browser compatible Web applications while significantly cutting their development time RadControls for ASPNET includes RadEditor RadTabstrip RadInputRadCalendar RadUpload RadWindow RadAjaxRadGrid RadCombobox RadMenu RadSpellRadChart RadTreeview and more

Single DeveloperParadise

TB3 01101A01$64899

dtSearch Engine for Win amp NETAdd dtSearchlsquos ldquoblazing speedsrdquo (CRN Test Center) searching and file format supportbull dozens of full-text and fielded

data search optionsbull file parsersconverters for hit-highlighted

display of all popular file typesbull Spider supports dynamic and static web data

highlights hits with links images etc intactbull API supports NET C++ Java SQL and more

new NET Spider API

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo mdashInfoWorld

programmerscomdtsearch

Single ServerParadise

D29 02101A07 $94999

New64-bit

Version

programmerscomsparxsystems

New Release

Enterprise Architect 71Visualize Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensiveintegrated UML 21 modeling suite providing key benefits at each stage ofsystem development Enterprise Architect71 supports UML SysML BPMN andother open standards to analyze designtest and construct reliable well under-stood systems Additional plug-ins arealso available for Zachman FrameworkMODAF DoDAF and TOGAF and to integrate with Eclipse and Visual Studio20052008

Corporate Edition1-4 Users

Paradise SP6 0001

$19699

programmerscommultiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers a powerful IDEwith its speed depth and support forover 50 languages Enhanced searchfunctions include Perl 5 RegularExpressions and definable filtersSupports large DOSWindows UNIXbinary and Mac files File SyncIntegration for Delphi 6 7 2005C++Builder 6 BDS 2006 and RadStudio2007 VB 6 VC 6 VS 2003 amp VS2005 Includes file compare code beautifying command maps and much more

1-49 UserParadise

A30 01201A02$16199

New Release

programmerscomlead

LEADTOOLS DocumentImaging v 16by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing document clean up high-speedscanning advanced compression (CCITTG3G4 JBIG2 MRC ABC) and morebull Multi-threaded OCRICROMR

MICRBarcodes (1D2D)bull Forms recognitionprocessingbull PDF and PDFAbull Annotation (Image Mark-up)bull CC++ NET WPF - Win3264

Paradise L05 03201A01$200799

New Version

16

programmerscomnsoftware

n software Red CarpetSubscriptions by n softwaren software Red Carpettrade Subscriptions giveyou everything in one package communica-tions components for every major Internet protocol SSL and SSH security SMIMEencryption Digital Certificates Credit CardProcessing ZIP compression InstantMessaging and even e-business (EDI) transactions NET Java COM C++ Delphieverything is included together with per developer licensing free quarterly update CDsand free upgrades during the subscription termParadise

D77 09101L01 $144499

programmerscomfaircom

c-treeACEtrade Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems desktop deployments andembedded devices for over 25 years bull Complete set of APIs including ADONET LINQ

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

including Windows UNIX Linux and Mac OS X

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

Paradise F01 0131

$71199

programmerscomvmware

View PremierParadise

V55 66101A01

CALLI

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

VDI Included

New Release

programmerscommindjet

for Windows 1 User

Paradise F15 17301A02

$29999

New Release

Mindjet MindManager 8by 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

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 Yoursquoll be able to work smarter and transform your ideas into action more quickly

Infragistics NetAdvantagefor NET 2008 Volume 3by Infragistics NetAdvantagereg for NET is our comprehensivesuite of ASPNET Windows Forms WPF and Silverlight line of business controls components and tools for the NET platformNetAdvantage for NET has what you need to add no-touch AJAX to your Web site awesome power and performance to yourWindows Forms application compelling userexperiences leveraging Windows PresentationFoundation and professionally polished userinterfaces (UI) Includes Annual Subscription and Source Code

Paradise I0M 02501F01 $103399

programmerscomacresso

Acresso InstallShield 2009Professional Windowsby AcressoInstallShield Professional Edition is a powerfulyet easy-to-use solution ideal for both noviceand seasoned installation developers Whilemost homegrown installation tools are not optimized for current industry standardsInstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesmdashincluding full support forWindows Vista

Paradise I21 02201A01 $168999

programmerscominfragistics

Project17 11909 525 PM Page 1

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 3: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Data visualization for every need every platform

Our most popular product Chart FX providescharts gauges and maps with additional verticalvisualization functionality for business intelligence(OLAP) geographic data financial technicalanalysis and statistical studies andformulas Recognized as the innovatorand leader of the charting componentcategory for the past 15 years Chart FXdelivers incomparable gallery optionsaesthetics and data analysis features

Grid FX was specifically designed for visual studiodevelopers to take advantage of a powerfuldesign-time experience integrated Chart FXfunctionality right in the box and AJAX toprovide robust run-time functionality in ASPnetapplications The dynamic aesthetic features for data presentation and analysis allow simpleadaptation to an existing application or to specificcorporate branding guidelines

PowerGadgets puts powerful IT monitoring on your desktop and in your data sidebarIT professionals can now create gadgetsthat consume data from WMI ExchangeSQL Server and even the Windows RegistryPowerGadgets does not require anydevelopment environments servers orbrowsers to run real-time gadget componentssuch as charts gauges and maps

To master the art of data visualization you must seek out the leader For almost two decadesSoftware FX has risen above all others by bringing top-of-the-line data visualization tools toenterprise developers working with diverse markets platforms and environments Thiswisdom has evolved into a vast body of products including a data presentation tool thatprovides a best-of-breed solution for Windows developers seeking enterprise quality andperformance as well as a professional IT monitoring solution offering incredible features forreporting and monitoring data For a world of data visualization products that can raise yourwork to a higher level depend on the source thatrsquos clearly on top

AchieveAHigherStateOfDataVisualization

Visit softwarefxcom for interactive demos and more information about our latest products

Project5 121108 443 PM Page 2

Project4 6208 1213 PM Page 1

wwwvisualstudiomagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 3

C CORNER

26 Use Lambda Expressions for Abstract DelegatesLambda expressions are nothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegateAnd more importantly what can you do about itBY BILL WAGNER

ON VB

32 Use Iterators in VB NowIterators are a crucial part of modern programmingnot least because they provide the basis for collection traversal using For Each loops Learn how to take advantage of them in your code withseveral different techniques for creating your owniterators in VB BY BILL MCCARTHY

DEPARTMENTS6 Editorrsquos Note BY PATRICK MEADER

10 Letters to the Editor

11 First LooksProduct Listings 11Review 13

39 Index of Advertisers

40 The Human FactorWhere Did All the Developers Go

BY DANIEL APPLEMAN

FEATURES

14 Retire Your Data CenterVisual Studio 2008 ASPNET and the Azure Services Platform combineto simplify local development of data-intensive Web apps and automatetheir deployment in Microsoft data centers The result You get maximizedavailability and reliability with almost limitless on-demand scalabilitywhile you pay only for resources consumed BY ROGER JENNINGS

COLUMNS

14

ldquoThe primary economic justificationfor moving data center activity intothe cloud is avoidance of capitalexpenditure for servers and associatednetworking hardware to handle peakinstead of average loadsrdquo

Roger Jennings ldquoRetire Your Data Centerrdquo p 14

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

ContentsFebruary 2009 bull VOLUME 19 bull NO 2

32

0209vsm_TOC_3-4v10 12209 133 PM Page 3

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom4

LEARN FROM THE PROSAs a developer you are constantly facing the problem of how to keep upwith all the new technologies beingreleased while still getting your jobdone You keep hearing about solutionsto your programming problems but the question is are they the rightsolutions for your particular needsYou could spend hours or even daystrying to find the answers yourself oryou could let the experts do it for youRedmond Media Group Events offers avariety of conferences and showswhere you can learn about new

technologies and what they might offer you attend in-depth workshops thatfocus on topics specific to your needs ask questions of the experts andinteract with your peers to discuss problems they face and what solutionstheyrsquove come up with Whether itrsquos Web design NET development or SQLServer programming wersquove got an event that matches your needs VisitRedmondEventscom to learn more about upcoming conferences and shows

ONLINE ARTICLES

Practical ASPNET Decoding RoutesIn his ongoing series on ASPNET Peter Vogel talks about the routingfeature included in Service Pack 1 for NET 35 and shows how to set upa site to use routes In this installment Vogel talks about the class filethat you must create to handle the conversion between the meaningfulURL provided by the user and the real path to your WebForm LOCATOR+ CODE VS0902PV1

Practical ASPNET Supporting RoutingIn this edition of Peter Vogelrsquos Practical ASPNET column he goes beyondthe basics of routing to look at some additional features The goals hereare to simplify your code and make life easier for your usersLOCATOR+ CODE VS0902PV2

ONLINE BLOGS

VSMrsquos Big IssueVisual Studio Magazinersquos Editor in Chief Patrick Meader and ManagingEditor Guy Wright have started a collaborative blog where they take alook at some of the bigger issues facing NET developers these days

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

VisualStudioMagazinecom

ContentThe blog will feature opinions and interviews with industryinsiders and pose questions designed to stimulate discussionCheck out their blog at VisualStudioMagazinecomLOCATOR+ CODE VS0901BI

ONLINE TUTORIALS

Classic VB Corner Executing DebuggablesHave you ever had one of those problems that only manifests itself in a compiled EXE that you simply canrsquotreproduce in the Classic Visual Basic IDE Or even worsethat only occurs on the clientrsquos machines and not onyours 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 RightConventional wisdom has it that version 1 of any Microsoftproduct or idea is really an alpha that version 2 is the betaand that the safe money rides on version 3 Then followingversion 3 Microsoft generally proceeds to do its best toupset the success it found in that golden release Karl EPeterson takes a trip down memory lane to one of the mostdurable version 3 products ever to come out of RedmondLOCATOR+ CODE VS0902KP2

NET NEWSLETTER SIGN-UPEvery week the NET Insight e-mail newsletter brings you up-to-date news technical information opinionsinterviews and analysis on topics and technologies such as Visual Basic NET C SQL Server and data accessASPNET wireless Web services and XML Sign up for free at VisualStudioMagazinecom

VirtualizationReviewcom1105 Media recently launcheda new Web site devoted exclusively to covering allaspects of IT virtualizationVirtualization Reviewcomhelps you harness the powerof virtualization by delivering

news and in-depth coverage of the products vendorsissues and technologies transforming IT through virtualization The site also features articles tips andtimely information about all aspects of virtualizationincluding servers storage desktops applications andmore Visit VirtualizationReviewcom now to start yourmove to a more efficient powerful virtual environment

0209vsm_TOC_3-4v10 12209 133 PM Page 4

programmersparadisecom800-445-7899

Your best source for software development tools

Prices subject to change Not responsible for typographical errors

reg

programmerscomtheimagingsource

Download a demo today

New Release

Professional EditionParadise

T79 02101A01$91999

bull NET WinForms control for VBNET and Cbull ActiveX for VB6 Delphi VBScriptHTML ASPbull File formats DOCX DOC RTF HTML XML TXTbull PDF export without additional 3rd party

tools or printer driversbull Nested tables headers amp footers text

frames bullets numbered lists multipleundoredo sections merge fields

bull Ready-to-use toolbars and dialog boxes

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

programmerscomtelerik

Telerik RadControlsby Telerik Add grid combo editing navigation and charting functionality to your AJAX and ASPNET projectsRadControls for ASPNET enhances your Web applications by adding AJAX functionality to yourASPNET projects The suite takes full advantage of the features included in Visual Studio 2005RadControls for ASPNET helps developers deliver feature-rich standards-compliant (WAI-A WCAG 10 XHTML 11) and cross-browser compatible Web applications while significantly cutting their development time RadControls for ASPNET includes RadEditor RadTabstrip RadInputRadCalendar RadUpload RadWindow RadAjaxRadGrid RadCombobox RadMenu RadSpellRadChart RadTreeview and more

Single DeveloperParadise

TB3 01101A01$64899

dtSearch Engine for Win amp NETAdd dtSearchlsquos ldquoblazing speedsrdquo (CRN Test Center) searching and file format supportbull dozens of full-text and fielded

data search optionsbull file parsersconverters for hit-highlighted

display of all popular file typesbull Spider supports dynamic and static web data

highlights hits with links images etc intactbull API supports NET C++ Java SQL and more

new NET Spider API

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo mdashInfoWorld

programmerscomdtsearch

Single ServerParadise

D29 02101A07 $94999

New64-bit

Version

programmerscomsparxsystems

New Release

Enterprise Architect 71Visualize Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensiveintegrated UML 21 modeling suite providing key benefits at each stage ofsystem development Enterprise Architect71 supports UML SysML BPMN andother open standards to analyze designtest and construct reliable well under-stood systems Additional plug-ins arealso available for Zachman FrameworkMODAF DoDAF and TOGAF and to integrate with Eclipse and Visual Studio20052008

Corporate Edition1-4 Users

Paradise SP6 0001

$19699

programmerscommultiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers a powerful IDEwith its speed depth and support forover 50 languages Enhanced searchfunctions include Perl 5 RegularExpressions and definable filtersSupports large DOSWindows UNIXbinary and Mac files File SyncIntegration for Delphi 6 7 2005C++Builder 6 BDS 2006 and RadStudio2007 VB 6 VC 6 VS 2003 amp VS2005 Includes file compare code beautifying command maps and much more

1-49 UserParadise

A30 01201A02$16199

New Release

programmerscomlead

LEADTOOLS DocumentImaging v 16by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing document clean up high-speedscanning advanced compression (CCITTG3G4 JBIG2 MRC ABC) and morebull Multi-threaded OCRICROMR

MICRBarcodes (1D2D)bull Forms recognitionprocessingbull PDF and PDFAbull Annotation (Image Mark-up)bull CC++ NET WPF - Win3264

Paradise L05 03201A01$200799

New Version

16

programmerscomnsoftware

n software Red CarpetSubscriptions by n softwaren software Red Carpettrade Subscriptions giveyou everything in one package communica-tions components for every major Internet protocol SSL and SSH security SMIMEencryption Digital Certificates Credit CardProcessing ZIP compression InstantMessaging and even e-business (EDI) transactions NET Java COM C++ Delphieverything is included together with per developer licensing free quarterly update CDsand free upgrades during the subscription termParadise

D77 09101L01 $144499

programmerscomfaircom

c-treeACEtrade Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems desktop deployments andembedded devices for over 25 years bull Complete set of APIs including ADONET LINQ

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

including Windows UNIX Linux and Mac OS X

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

Paradise F01 0131

$71199

programmerscomvmware

View PremierParadise

V55 66101A01

CALLI

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

VDI Included

New Release

programmerscommindjet

for Windows 1 User

Paradise F15 17301A02

$29999

New Release

Mindjet MindManager 8by 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

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 Yoursquoll be able to work smarter and transform your ideas into action more quickly

Infragistics NetAdvantagefor NET 2008 Volume 3by Infragistics NetAdvantagereg for NET is our comprehensivesuite of ASPNET Windows Forms WPF and Silverlight line of business controls components and tools for the NET platformNetAdvantage for NET has what you need to add no-touch AJAX to your Web site awesome power and performance to yourWindows Forms application compelling userexperiences leveraging Windows PresentationFoundation and professionally polished userinterfaces (UI) Includes Annual Subscription and Source Code

Paradise I0M 02501F01 $103399

programmerscomacresso

Acresso InstallShield 2009Professional Windowsby AcressoInstallShield Professional Edition is a powerfulyet easy-to-use solution ideal for both noviceand seasoned installation developers Whilemost homegrown installation tools are not optimized for current industry standardsInstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesmdashincluding full support forWindows Vista

Paradise I21 02201A01 $168999

programmerscominfragistics

Project17 11909 525 PM Page 1

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 4: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Project4 6208 1213 PM Page 1

wwwvisualstudiomagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 3

C CORNER

26 Use Lambda Expressions for Abstract DelegatesLambda expressions are nothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegateAnd more importantly what can you do about itBY BILL WAGNER

ON VB

32 Use Iterators in VB NowIterators are a crucial part of modern programmingnot least because they provide the basis for collection traversal using For Each loops Learn how to take advantage of them in your code withseveral different techniques for creating your owniterators in VB BY BILL MCCARTHY

DEPARTMENTS6 Editorrsquos Note BY PATRICK MEADER

10 Letters to the Editor

11 First LooksProduct Listings 11Review 13

39 Index of Advertisers

40 The Human FactorWhere Did All the Developers Go

BY DANIEL APPLEMAN

FEATURES

14 Retire Your Data CenterVisual Studio 2008 ASPNET and the Azure Services Platform combineto simplify local development of data-intensive Web apps and automatetheir deployment in Microsoft data centers The result You get maximizedavailability and reliability with almost limitless on-demand scalabilitywhile you pay only for resources consumed BY ROGER JENNINGS

COLUMNS

14

ldquoThe primary economic justificationfor moving data center activity intothe cloud is avoidance of capitalexpenditure for servers and associatednetworking hardware to handle peakinstead of average loadsrdquo

Roger Jennings ldquoRetire Your Data Centerrdquo p 14

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

ContentsFebruary 2009 bull VOLUME 19 bull NO 2

32

0209vsm_TOC_3-4v10 12209 133 PM Page 3

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom4

LEARN FROM THE PROSAs a developer you are constantly facing the problem of how to keep upwith all the new technologies beingreleased while still getting your jobdone You keep hearing about solutionsto your programming problems but the question is are they the rightsolutions for your particular needsYou could spend hours or even daystrying to find the answers yourself oryou could let the experts do it for youRedmond Media Group Events offers avariety of conferences and showswhere you can learn about new

technologies and what they might offer you attend in-depth workshops thatfocus on topics specific to your needs ask questions of the experts andinteract with your peers to discuss problems they face and what solutionstheyrsquove come up with Whether itrsquos Web design NET development or SQLServer programming wersquove got an event that matches your needs VisitRedmondEventscom to learn more about upcoming conferences and shows

ONLINE ARTICLES

Practical ASPNET Decoding RoutesIn his ongoing series on ASPNET Peter Vogel talks about the routingfeature included in Service Pack 1 for NET 35 and shows how to set upa site to use routes In this installment Vogel talks about the class filethat you must create to handle the conversion between the meaningfulURL provided by the user and the real path to your WebForm LOCATOR+ CODE VS0902PV1

Practical ASPNET Supporting RoutingIn this edition of Peter Vogelrsquos Practical ASPNET column he goes beyondthe basics of routing to look at some additional features The goals hereare to simplify your code and make life easier for your usersLOCATOR+ CODE VS0902PV2

ONLINE BLOGS

VSMrsquos Big IssueVisual Studio Magazinersquos Editor in Chief Patrick Meader and ManagingEditor Guy Wright have started a collaborative blog where they take alook at some of the bigger issues facing NET developers these days

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

VisualStudioMagazinecom

ContentThe blog will feature opinions and interviews with industryinsiders and pose questions designed to stimulate discussionCheck out their blog at VisualStudioMagazinecomLOCATOR+ CODE VS0901BI

ONLINE TUTORIALS

Classic VB Corner Executing DebuggablesHave you ever had one of those problems that only manifests itself in a compiled EXE that you simply canrsquotreproduce in the Classic Visual Basic IDE Or even worsethat only occurs on the clientrsquos machines and not onyours 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 RightConventional wisdom has it that version 1 of any Microsoftproduct or idea is really an alpha that version 2 is the betaand that the safe money rides on version 3 Then followingversion 3 Microsoft generally proceeds to do its best toupset the success it found in that golden release Karl EPeterson takes a trip down memory lane to one of the mostdurable version 3 products ever to come out of RedmondLOCATOR+ CODE VS0902KP2

NET NEWSLETTER SIGN-UPEvery week the NET Insight e-mail newsletter brings you up-to-date news technical information opinionsinterviews and analysis on topics and technologies such as Visual Basic NET C SQL Server and data accessASPNET wireless Web services and XML Sign up for free at VisualStudioMagazinecom

VirtualizationReviewcom1105 Media recently launcheda new Web site devoted exclusively to covering allaspects of IT virtualizationVirtualization Reviewcomhelps you harness the powerof virtualization by delivering

news and in-depth coverage of the products vendorsissues and technologies transforming IT through virtualization The site also features articles tips andtimely information about all aspects of virtualizationincluding servers storage desktops applications andmore Visit VirtualizationReviewcom now to start yourmove to a more efficient powerful virtual environment

0209vsm_TOC_3-4v10 12209 133 PM Page 4

programmersparadisecom800-445-7899

Your best source for software development tools

Prices subject to change Not responsible for typographical errors

reg

programmerscomtheimagingsource

Download a demo today

New Release

Professional EditionParadise

T79 02101A01$91999

bull NET WinForms control for VBNET and Cbull ActiveX for VB6 Delphi VBScriptHTML ASPbull File formats DOCX DOC RTF HTML XML TXTbull PDF export without additional 3rd party

tools or printer driversbull Nested tables headers amp footers text

frames bullets numbered lists multipleundoredo sections merge fields

bull Ready-to-use toolbars and dialog boxes

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

programmerscomtelerik

Telerik RadControlsby Telerik Add grid combo editing navigation and charting functionality to your AJAX and ASPNET projectsRadControls for ASPNET enhances your Web applications by adding AJAX functionality to yourASPNET projects The suite takes full advantage of the features included in Visual Studio 2005RadControls for ASPNET helps developers deliver feature-rich standards-compliant (WAI-A WCAG 10 XHTML 11) and cross-browser compatible Web applications while significantly cutting their development time RadControls for ASPNET includes RadEditor RadTabstrip RadInputRadCalendar RadUpload RadWindow RadAjaxRadGrid RadCombobox RadMenu RadSpellRadChart RadTreeview and more

Single DeveloperParadise

TB3 01101A01$64899

dtSearch Engine for Win amp NETAdd dtSearchlsquos ldquoblazing speedsrdquo (CRN Test Center) searching and file format supportbull dozens of full-text and fielded

data search optionsbull file parsersconverters for hit-highlighted

display of all popular file typesbull Spider supports dynamic and static web data

highlights hits with links images etc intactbull API supports NET C++ Java SQL and more

new NET Spider API

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo mdashInfoWorld

programmerscomdtsearch

Single ServerParadise

D29 02101A07 $94999

New64-bit

Version

programmerscomsparxsystems

New Release

Enterprise Architect 71Visualize Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensiveintegrated UML 21 modeling suite providing key benefits at each stage ofsystem development Enterprise Architect71 supports UML SysML BPMN andother open standards to analyze designtest and construct reliable well under-stood systems Additional plug-ins arealso available for Zachman FrameworkMODAF DoDAF and TOGAF and to integrate with Eclipse and Visual Studio20052008

Corporate Edition1-4 Users

Paradise SP6 0001

$19699

programmerscommultiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers a powerful IDEwith its speed depth and support forover 50 languages Enhanced searchfunctions include Perl 5 RegularExpressions and definable filtersSupports large DOSWindows UNIXbinary and Mac files File SyncIntegration for Delphi 6 7 2005C++Builder 6 BDS 2006 and RadStudio2007 VB 6 VC 6 VS 2003 amp VS2005 Includes file compare code beautifying command maps and much more

1-49 UserParadise

A30 01201A02$16199

New Release

programmerscomlead

LEADTOOLS DocumentImaging v 16by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing document clean up high-speedscanning advanced compression (CCITTG3G4 JBIG2 MRC ABC) and morebull Multi-threaded OCRICROMR

MICRBarcodes (1D2D)bull Forms recognitionprocessingbull PDF and PDFAbull Annotation (Image Mark-up)bull CC++ NET WPF - Win3264

Paradise L05 03201A01$200799

New Version

16

programmerscomnsoftware

n software Red CarpetSubscriptions by n softwaren software Red Carpettrade Subscriptions giveyou everything in one package communica-tions components for every major Internet protocol SSL and SSH security SMIMEencryption Digital Certificates Credit CardProcessing ZIP compression InstantMessaging and even e-business (EDI) transactions NET Java COM C++ Delphieverything is included together with per developer licensing free quarterly update CDsand free upgrades during the subscription termParadise

D77 09101L01 $144499

programmerscomfaircom

c-treeACEtrade Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems desktop deployments andembedded devices for over 25 years bull Complete set of APIs including ADONET LINQ

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

including Windows UNIX Linux and Mac OS X

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

Paradise F01 0131

$71199

programmerscomvmware

View PremierParadise

V55 66101A01

CALLI

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

VDI Included

New Release

programmerscommindjet

for Windows 1 User

Paradise F15 17301A02

$29999

New Release

Mindjet MindManager 8by 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

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 Yoursquoll be able to work smarter and transform your ideas into action more quickly

Infragistics NetAdvantagefor NET 2008 Volume 3by Infragistics NetAdvantagereg for NET is our comprehensivesuite of ASPNET Windows Forms WPF and Silverlight line of business controls components and tools for the NET platformNetAdvantage for NET has what you need to add no-touch AJAX to your Web site awesome power and performance to yourWindows Forms application compelling userexperiences leveraging Windows PresentationFoundation and professionally polished userinterfaces (UI) Includes Annual Subscription and Source Code

Paradise I0M 02501F01 $103399

programmerscomacresso

Acresso InstallShield 2009Professional Windowsby AcressoInstallShield Professional Edition is a powerfulyet easy-to-use solution ideal for both noviceand seasoned installation developers Whilemost homegrown installation tools are not optimized for current industry standardsInstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesmdashincluding full support forWindows Vista

Paradise I21 02201A01 $168999

programmerscominfragistics

Project17 11909 525 PM Page 1

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 5: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

wwwvisualstudiomagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 3

C CORNER

26 Use Lambda Expressions for Abstract DelegatesLambda expressions are nothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegateAnd more importantly what can you do about itBY BILL WAGNER

ON VB

32 Use Iterators in VB NowIterators are a crucial part of modern programmingnot least because they provide the basis for collection traversal using For Each loops Learn how to take advantage of them in your code withseveral different techniques for creating your owniterators in VB BY BILL MCCARTHY

DEPARTMENTS6 Editorrsquos Note BY PATRICK MEADER

10 Letters to the Editor

11 First LooksProduct Listings 11Review 13

39 Index of Advertisers

40 The Human FactorWhere Did All the Developers Go

BY DANIEL APPLEMAN

FEATURES

14 Retire Your Data CenterVisual Studio 2008 ASPNET and the Azure Services Platform combineto simplify local development of data-intensive Web apps and automatetheir deployment in Microsoft data centers The result You get maximizedavailability and reliability with almost limitless on-demand scalabilitywhile you pay only for resources consumed BY ROGER JENNINGS

COLUMNS

14

ldquoThe primary economic justificationfor moving data center activity intothe cloud is avoidance of capitalexpenditure for servers and associatednetworking hardware to handle peakinstead of average loadsrdquo

Roger Jennings ldquoRetire Your Data Centerrdquo p 14

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

ContentsFebruary 2009 bull VOLUME 19 bull NO 2

32

0209vsm_TOC_3-4v10 12209 133 PM Page 3

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom4

LEARN FROM THE PROSAs a developer you are constantly facing the problem of how to keep upwith all the new technologies beingreleased while still getting your jobdone You keep hearing about solutionsto your programming problems but the question is are they the rightsolutions for your particular needsYou could spend hours or even daystrying to find the answers yourself oryou could let the experts do it for youRedmond Media Group Events offers avariety of conferences and showswhere you can learn about new

technologies and what they might offer you attend in-depth workshops thatfocus on topics specific to your needs ask questions of the experts andinteract with your peers to discuss problems they face and what solutionstheyrsquove come up with Whether itrsquos Web design NET development or SQLServer programming wersquove got an event that matches your needs VisitRedmondEventscom to learn more about upcoming conferences and shows

ONLINE ARTICLES

Practical ASPNET Decoding RoutesIn his ongoing series on ASPNET Peter Vogel talks about the routingfeature included in Service Pack 1 for NET 35 and shows how to set upa site to use routes In this installment Vogel talks about the class filethat you must create to handle the conversion between the meaningfulURL provided by the user and the real path to your WebForm LOCATOR+ CODE VS0902PV1

Practical ASPNET Supporting RoutingIn this edition of Peter Vogelrsquos Practical ASPNET column he goes beyondthe basics of routing to look at some additional features The goals hereare to simplify your code and make life easier for your usersLOCATOR+ CODE VS0902PV2

ONLINE BLOGS

VSMrsquos Big IssueVisual Studio Magazinersquos Editor in Chief Patrick Meader and ManagingEditor Guy Wright have started a collaborative blog where they take alook at some of the bigger issues facing NET developers these days

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

VisualStudioMagazinecom

ContentThe blog will feature opinions and interviews with industryinsiders and pose questions designed to stimulate discussionCheck out their blog at VisualStudioMagazinecomLOCATOR+ CODE VS0901BI

ONLINE TUTORIALS

Classic VB Corner Executing DebuggablesHave you ever had one of those problems that only manifests itself in a compiled EXE that you simply canrsquotreproduce in the Classic Visual Basic IDE Or even worsethat only occurs on the clientrsquos machines and not onyours 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 RightConventional wisdom has it that version 1 of any Microsoftproduct or idea is really an alpha that version 2 is the betaand that the safe money rides on version 3 Then followingversion 3 Microsoft generally proceeds to do its best toupset the success it found in that golden release Karl EPeterson takes a trip down memory lane to one of the mostdurable version 3 products ever to come out of RedmondLOCATOR+ CODE VS0902KP2

NET NEWSLETTER SIGN-UPEvery week the NET Insight e-mail newsletter brings you up-to-date news technical information opinionsinterviews and analysis on topics and technologies such as Visual Basic NET C SQL Server and data accessASPNET wireless Web services and XML Sign up for free at VisualStudioMagazinecom

VirtualizationReviewcom1105 Media recently launcheda new Web site devoted exclusively to covering allaspects of IT virtualizationVirtualization Reviewcomhelps you harness the powerof virtualization by delivering

news and in-depth coverage of the products vendorsissues and technologies transforming IT through virtualization The site also features articles tips andtimely information about all aspects of virtualizationincluding servers storage desktops applications andmore Visit VirtualizationReviewcom now to start yourmove to a more efficient powerful virtual environment

0209vsm_TOC_3-4v10 12209 133 PM Page 4

programmersparadisecom800-445-7899

Your best source for software development tools

Prices subject to change Not responsible for typographical errors

reg

programmerscomtheimagingsource

Download a demo today

New Release

Professional EditionParadise

T79 02101A01$91999

bull NET WinForms control for VBNET and Cbull ActiveX for VB6 Delphi VBScriptHTML ASPbull File formats DOCX DOC RTF HTML XML TXTbull PDF export without additional 3rd party

tools or printer driversbull Nested tables headers amp footers text

frames bullets numbered lists multipleundoredo sections merge fields

bull Ready-to-use toolbars and dialog boxes

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

programmerscomtelerik

Telerik RadControlsby Telerik Add grid combo editing navigation and charting functionality to your AJAX and ASPNET projectsRadControls for ASPNET enhances your Web applications by adding AJAX functionality to yourASPNET projects The suite takes full advantage of the features included in Visual Studio 2005RadControls for ASPNET helps developers deliver feature-rich standards-compliant (WAI-A WCAG 10 XHTML 11) and cross-browser compatible Web applications while significantly cutting their development time RadControls for ASPNET includes RadEditor RadTabstrip RadInputRadCalendar RadUpload RadWindow RadAjaxRadGrid RadCombobox RadMenu RadSpellRadChart RadTreeview and more

Single DeveloperParadise

TB3 01101A01$64899

dtSearch Engine for Win amp NETAdd dtSearchlsquos ldquoblazing speedsrdquo (CRN Test Center) searching and file format supportbull dozens of full-text and fielded

data search optionsbull file parsersconverters for hit-highlighted

display of all popular file typesbull Spider supports dynamic and static web data

highlights hits with links images etc intactbull API supports NET C++ Java SQL and more

new NET Spider API

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo mdashInfoWorld

programmerscomdtsearch

Single ServerParadise

D29 02101A07 $94999

New64-bit

Version

programmerscomsparxsystems

New Release

Enterprise Architect 71Visualize Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensiveintegrated UML 21 modeling suite providing key benefits at each stage ofsystem development Enterprise Architect71 supports UML SysML BPMN andother open standards to analyze designtest and construct reliable well under-stood systems Additional plug-ins arealso available for Zachman FrameworkMODAF DoDAF and TOGAF and to integrate with Eclipse and Visual Studio20052008

Corporate Edition1-4 Users

Paradise SP6 0001

$19699

programmerscommultiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers a powerful IDEwith its speed depth and support forover 50 languages Enhanced searchfunctions include Perl 5 RegularExpressions and definable filtersSupports large DOSWindows UNIXbinary and Mac files File SyncIntegration for Delphi 6 7 2005C++Builder 6 BDS 2006 and RadStudio2007 VB 6 VC 6 VS 2003 amp VS2005 Includes file compare code beautifying command maps and much more

1-49 UserParadise

A30 01201A02$16199

New Release

programmerscomlead

LEADTOOLS DocumentImaging v 16by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing document clean up high-speedscanning advanced compression (CCITTG3G4 JBIG2 MRC ABC) and morebull Multi-threaded OCRICROMR

MICRBarcodes (1D2D)bull Forms recognitionprocessingbull PDF and PDFAbull Annotation (Image Mark-up)bull CC++ NET WPF - Win3264

Paradise L05 03201A01$200799

New Version

16

programmerscomnsoftware

n software Red CarpetSubscriptions by n softwaren software Red Carpettrade Subscriptions giveyou everything in one package communica-tions components for every major Internet protocol SSL and SSH security SMIMEencryption Digital Certificates Credit CardProcessing ZIP compression InstantMessaging and even e-business (EDI) transactions NET Java COM C++ Delphieverything is included together with per developer licensing free quarterly update CDsand free upgrades during the subscription termParadise

D77 09101L01 $144499

programmerscomfaircom

c-treeACEtrade Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems desktop deployments andembedded devices for over 25 years bull Complete set of APIs including ADONET LINQ

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

including Windows UNIX Linux and Mac OS X

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

Paradise F01 0131

$71199

programmerscomvmware

View PremierParadise

V55 66101A01

CALLI

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

VDI Included

New Release

programmerscommindjet

for Windows 1 User

Paradise F15 17301A02

$29999

New Release

Mindjet MindManager 8by 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

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 Yoursquoll be able to work smarter and transform your ideas into action more quickly

Infragistics NetAdvantagefor NET 2008 Volume 3by Infragistics NetAdvantagereg for NET is our comprehensivesuite of ASPNET Windows Forms WPF and Silverlight line of business controls components and tools for the NET platformNetAdvantage for NET has what you need to add no-touch AJAX to your Web site awesome power and performance to yourWindows Forms application compelling userexperiences leveraging Windows PresentationFoundation and professionally polished userinterfaces (UI) Includes Annual Subscription and Source Code

Paradise I0M 02501F01 $103399

programmerscomacresso

Acresso InstallShield 2009Professional Windowsby AcressoInstallShield Professional Edition is a powerfulyet easy-to-use solution ideal for both noviceand seasoned installation developers Whilemost homegrown installation tools are not optimized for current industry standardsInstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesmdashincluding full support forWindows Vista

Paradise I21 02201A01 $168999

programmerscominfragistics

Project17 11909 525 PM Page 1

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 6: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom4

LEARN FROM THE PROSAs a developer you are constantly facing the problem of how to keep upwith all the new technologies beingreleased while still getting your jobdone You keep hearing about solutionsto your programming problems but the question is are they the rightsolutions for your particular needsYou could spend hours or even daystrying to find the answers yourself oryou could let the experts do it for youRedmond Media Group Events offers avariety of conferences and showswhere you can learn about new

technologies and what they might offer you attend in-depth workshops thatfocus on topics specific to your needs ask questions of the experts andinteract with your peers to discuss problems they face and what solutionstheyrsquove come up with Whether itrsquos Web design NET development or SQLServer programming wersquove got an event that matches your needs VisitRedmondEventscom to learn more about upcoming conferences and shows

ONLINE ARTICLES

Practical ASPNET Decoding RoutesIn his ongoing series on ASPNET Peter Vogel talks about the routingfeature included in Service Pack 1 for NET 35 and shows how to set upa site to use routes In this installment Vogel talks about the class filethat you must create to handle the conversion between the meaningfulURL provided by the user and the real path to your WebForm LOCATOR+ CODE VS0902PV1

Practical ASPNET Supporting RoutingIn this edition of Peter Vogelrsquos Practical ASPNET column he goes beyondthe basics of routing to look at some additional features The goals hereare to simplify your code and make life easier for your usersLOCATOR+ CODE VS0902PV2

ONLINE BLOGS

VSMrsquos Big IssueVisual Studio Magazinersquos Editor in Chief Patrick Meader and ManagingEditor Guy Wright have started a collaborative blog where they take alook at some of the bigger issues facing NET developers these days

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

VisualStudioMagazinecom

ContentThe blog will feature opinions and interviews with industryinsiders and pose questions designed to stimulate discussionCheck out their blog at VisualStudioMagazinecomLOCATOR+ CODE VS0901BI

ONLINE TUTORIALS

Classic VB Corner Executing DebuggablesHave you ever had one of those problems that only manifests itself in a compiled EXE that you simply canrsquotreproduce in the Classic Visual Basic IDE Or even worsethat only occurs on the clientrsquos machines and not onyours 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 RightConventional wisdom has it that version 1 of any Microsoftproduct or idea is really an alpha that version 2 is the betaand that the safe money rides on version 3 Then followingversion 3 Microsoft generally proceeds to do its best toupset the success it found in that golden release Karl EPeterson takes a trip down memory lane to one of the mostdurable version 3 products ever to come out of RedmondLOCATOR+ CODE VS0902KP2

NET NEWSLETTER SIGN-UPEvery week the NET Insight e-mail newsletter brings you up-to-date news technical information opinionsinterviews and analysis on topics and technologies such as Visual Basic NET C SQL Server and data accessASPNET wireless Web services and XML Sign up for free at VisualStudioMagazinecom

VirtualizationReviewcom1105 Media recently launcheda new Web site devoted exclusively to covering allaspects of IT virtualizationVirtualization Reviewcomhelps you harness the powerof virtualization by delivering

news and in-depth coverage of the products vendorsissues and technologies transforming IT through virtualization The site also features articles tips andtimely information about all aspects of virtualizationincluding servers storage desktops applications andmore Visit VirtualizationReviewcom now to start yourmove to a more efficient powerful virtual environment

0209vsm_TOC_3-4v10 12209 133 PM Page 4

programmersparadisecom800-445-7899

Your best source for software development tools

Prices subject to change Not responsible for typographical errors

reg

programmerscomtheimagingsource

Download a demo today

New Release

Professional EditionParadise

T79 02101A01$91999

bull NET WinForms control for VBNET and Cbull ActiveX for VB6 Delphi VBScriptHTML ASPbull File formats DOCX DOC RTF HTML XML TXTbull PDF export without additional 3rd party

tools or printer driversbull Nested tables headers amp footers text

frames bullets numbered lists multipleundoredo sections merge fields

bull Ready-to-use toolbars and dialog boxes

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

programmerscomtelerik

Telerik RadControlsby Telerik Add grid combo editing navigation and charting functionality to your AJAX and ASPNET projectsRadControls for ASPNET enhances your Web applications by adding AJAX functionality to yourASPNET projects The suite takes full advantage of the features included in Visual Studio 2005RadControls for ASPNET helps developers deliver feature-rich standards-compliant (WAI-A WCAG 10 XHTML 11) and cross-browser compatible Web applications while significantly cutting their development time RadControls for ASPNET includes RadEditor RadTabstrip RadInputRadCalendar RadUpload RadWindow RadAjaxRadGrid RadCombobox RadMenu RadSpellRadChart RadTreeview and more

Single DeveloperParadise

TB3 01101A01$64899

dtSearch Engine for Win amp NETAdd dtSearchlsquos ldquoblazing speedsrdquo (CRN Test Center) searching and file format supportbull dozens of full-text and fielded

data search optionsbull file parsersconverters for hit-highlighted

display of all popular file typesbull Spider supports dynamic and static web data

highlights hits with links images etc intactbull API supports NET C++ Java SQL and more

new NET Spider API

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo mdashInfoWorld

programmerscomdtsearch

Single ServerParadise

D29 02101A07 $94999

New64-bit

Version

programmerscomsparxsystems

New Release

Enterprise Architect 71Visualize Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensiveintegrated UML 21 modeling suite providing key benefits at each stage ofsystem development Enterprise Architect71 supports UML SysML BPMN andother open standards to analyze designtest and construct reliable well under-stood systems Additional plug-ins arealso available for Zachman FrameworkMODAF DoDAF and TOGAF and to integrate with Eclipse and Visual Studio20052008

Corporate Edition1-4 Users

Paradise SP6 0001

$19699

programmerscommultiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers a powerful IDEwith its speed depth and support forover 50 languages Enhanced searchfunctions include Perl 5 RegularExpressions and definable filtersSupports large DOSWindows UNIXbinary and Mac files File SyncIntegration for Delphi 6 7 2005C++Builder 6 BDS 2006 and RadStudio2007 VB 6 VC 6 VS 2003 amp VS2005 Includes file compare code beautifying command maps and much more

1-49 UserParadise

A30 01201A02$16199

New Release

programmerscomlead

LEADTOOLS DocumentImaging v 16by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing document clean up high-speedscanning advanced compression (CCITTG3G4 JBIG2 MRC ABC) and morebull Multi-threaded OCRICROMR

MICRBarcodes (1D2D)bull Forms recognitionprocessingbull PDF and PDFAbull Annotation (Image Mark-up)bull CC++ NET WPF - Win3264

Paradise L05 03201A01$200799

New Version

16

programmerscomnsoftware

n software Red CarpetSubscriptions by n softwaren software Red Carpettrade Subscriptions giveyou everything in one package communica-tions components for every major Internet protocol SSL and SSH security SMIMEencryption Digital Certificates Credit CardProcessing ZIP compression InstantMessaging and even e-business (EDI) transactions NET Java COM C++ Delphieverything is included together with per developer licensing free quarterly update CDsand free upgrades during the subscription termParadise

D77 09101L01 $144499

programmerscomfaircom

c-treeACEtrade Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems desktop deployments andembedded devices for over 25 years bull Complete set of APIs including ADONET LINQ

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

including Windows UNIX Linux and Mac OS X

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

Paradise F01 0131

$71199

programmerscomvmware

View PremierParadise

V55 66101A01

CALLI

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

VDI Included

New Release

programmerscommindjet

for Windows 1 User

Paradise F15 17301A02

$29999

New Release

Mindjet MindManager 8by 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

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 Yoursquoll be able to work smarter and transform your ideas into action more quickly

Infragistics NetAdvantagefor NET 2008 Volume 3by Infragistics NetAdvantagereg for NET is our comprehensivesuite of ASPNET Windows Forms WPF and Silverlight line of business controls components and tools for the NET platformNetAdvantage for NET has what you need to add no-touch AJAX to your Web site awesome power and performance to yourWindows Forms application compelling userexperiences leveraging Windows PresentationFoundation and professionally polished userinterfaces (UI) Includes Annual Subscription and Source Code

Paradise I0M 02501F01 $103399

programmerscomacresso

Acresso InstallShield 2009Professional Windowsby AcressoInstallShield Professional Edition is a powerfulyet easy-to-use solution ideal for both noviceand seasoned installation developers Whilemost homegrown installation tools are not optimized for current industry standardsInstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesmdashincluding full support forWindows Vista

Paradise I21 02201A01 $168999

programmerscominfragistics

Project17 11909 525 PM Page 1

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 7: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

programmersparadisecom800-445-7899

Your best source for software development tools

Prices subject to change Not responsible for typographical errors

reg

programmerscomtheimagingsource

Download a demo today

New Release

Professional EditionParadise

T79 02101A01$91999

bull NET WinForms control for VBNET and Cbull ActiveX for VB6 Delphi VBScriptHTML ASPbull File formats DOCX DOC RTF HTML XML TXTbull PDF export without additional 3rd party

tools or printer driversbull Nested tables headers amp footers text

frames bullets numbered lists multipleundoredo sections merge fields

bull Ready-to-use toolbars and dialog boxes

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

programmerscomtelerik

Telerik RadControlsby Telerik Add grid combo editing navigation and charting functionality to your AJAX and ASPNET projectsRadControls for ASPNET enhances your Web applications by adding AJAX functionality to yourASPNET projects The suite takes full advantage of the features included in Visual Studio 2005RadControls for ASPNET helps developers deliver feature-rich standards-compliant (WAI-A WCAG 10 XHTML 11) and cross-browser compatible Web applications while significantly cutting their development time RadControls for ASPNET includes RadEditor RadTabstrip RadInputRadCalendar RadUpload RadWindow RadAjaxRadGrid RadCombobox RadMenu RadSpellRadChart RadTreeview and more

Single DeveloperParadise

TB3 01101A01$64899

dtSearch Engine for Win amp NETAdd dtSearchlsquos ldquoblazing speedsrdquo (CRN Test Center) searching and file format supportbull dozens of full-text and fielded

data search optionsbull file parsersconverters for hit-highlighted

display of all popular file typesbull Spider supports dynamic and static web data

highlights hits with links images etc intactbull API supports NET C++ Java SQL and more

new NET Spider API

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo mdashInfoWorld

programmerscomdtsearch

Single ServerParadise

D29 02101A07 $94999

New64-bit

Version

programmerscomsparxsystems

New Release

Enterprise Architect 71Visualize Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensiveintegrated UML 21 modeling suite providing key benefits at each stage ofsystem development Enterprise Architect71 supports UML SysML BPMN andother open standards to analyze designtest and construct reliable well under-stood systems Additional plug-ins arealso available for Zachman FrameworkMODAF DoDAF and TOGAF and to integrate with Eclipse and Visual Studio20052008

Corporate Edition1-4 Users

Paradise SP6 0001

$19699

programmerscommultiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers a powerful IDEwith its speed depth and support forover 50 languages Enhanced searchfunctions include Perl 5 RegularExpressions and definable filtersSupports large DOSWindows UNIXbinary and Mac files File SyncIntegration for Delphi 6 7 2005C++Builder 6 BDS 2006 and RadStudio2007 VB 6 VC 6 VS 2003 amp VS2005 Includes file compare code beautifying command maps and much more

1-49 UserParadise

A30 01201A02$16199

New Release

programmerscomlead

LEADTOOLS DocumentImaging v 16by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing document clean up high-speedscanning advanced compression (CCITTG3G4 JBIG2 MRC ABC) and morebull Multi-threaded OCRICROMR

MICRBarcodes (1D2D)bull Forms recognitionprocessingbull PDF and PDFAbull Annotation (Image Mark-up)bull CC++ NET WPF - Win3264

Paradise L05 03201A01$200799

New Version

16

programmerscomnsoftware

n software Red CarpetSubscriptions by n softwaren software Red Carpettrade Subscriptions giveyou everything in one package communica-tions components for every major Internet protocol SSL and SSH security SMIMEencryption Digital Certificates Credit CardProcessing ZIP compression InstantMessaging and even e-business (EDI) transactions NET Java COM C++ Delphieverything is included together with per developer licensing free quarterly update CDsand free upgrades during the subscription termParadise

D77 09101L01 $144499

programmerscomfaircom

c-treeACEtrade Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems desktop deployments andembedded devices for over 25 years bull Complete set of APIs including ADONET LINQ

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

including Windows UNIX Linux and Mac OS X

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

Paradise F01 0131

$71199

programmerscomvmware

View PremierParadise

V55 66101A01

CALLI

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

VDI Included

New Release

programmerscommindjet

for Windows 1 User

Paradise F15 17301A02

$29999

New Release

Mindjet MindManager 8by 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

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 Yoursquoll be able to work smarter and transform your ideas into action more quickly

Infragistics NetAdvantagefor NET 2008 Volume 3by Infragistics NetAdvantagereg for NET is our comprehensivesuite of ASPNET Windows Forms WPF and Silverlight line of business controls components and tools for the NET platformNetAdvantage for NET has what you need to add no-touch AJAX to your Web site awesome power and performance to yourWindows Forms application compelling userexperiences leveraging Windows PresentationFoundation and professionally polished userinterfaces (UI) Includes Annual Subscription and Source Code

Paradise I0M 02501F01 $103399

programmerscomacresso

Acresso InstallShield 2009Professional Windowsby AcressoInstallShield Professional Edition is a powerfulyet easy-to-use solution ideal for both noviceand seasoned installation developers Whilemost homegrown installation tools are not optimized for current industry standardsInstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesmdashincluding full support forWindows Vista

Paradise I21 02201A01 $168999

programmerscominfragistics

Project17 11909 525 PM Page 1

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 8: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Editorrsquos Note

BY PATRICK MEADEReditor in chief

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom6

CALCULATING THE COST OF CHANGEI hate doing something twice especially if I perceive that redoing somethingismdashor should bemdashunnecessarySometimes a portable USB storage device givesout or a file gets corruptedand I find myself needing to reproduce content orredo an edit Irsquove already doneIt doesnrsquot happen oftenbut it hap-pensand I tend to react to such events in a consistent manner

I curse fiercely I berate myself for not taking better pre-cautions Then I curse some more as I try to rescue the fileWill it open in notepad perhaps Will a different USB port beable to see the portable storage device Experience tells me Irsquombetter off knuckling down and just getting to workbut Irsquom usu-ally too worked up to sit down and start anew immediately Ishould take up yoga or meditation learn a calming mantra Abetter man might seek solace from his spouse but I donrsquot wantsympathy or empathy at such times No I want to break stuffto throw the offending computer out the window I want tosmash things

Given how much I hate to redo stuff I know one thingdefinitively Irsquod hate to be a developer Having to revisit andrewrite a half-dozen applications every time the company thatmakes my software tools changes something would leave mefeeling queasy having to retool everything Irsquove ever donebecause of far-reaching changes would mean a weeks- if notmonths-long stream of invectives to make David Mametblush Irsquod be in a semi-permanent rage state tucked away in aback office or closet so no one else would have to listen to meItrsquos one thing to redo something because I made an error itrsquosquite another to be forced to redo something because some-one else makes a change thatrsquos in my ldquobest interestsrdquoespeciallyif that change alters how I must approach my job

But such changes happen all too often in software devel-opment In her column last issue (Ask Kathleen ldquoWindowsWorkflow Changes Directionrdquo January 2009) Kathleen Dol-lard tackled the extensive changes Microsoft is making in thenext version of Windows Workflow Foundation (WF) Shenoted how many of the changes planned for version 4 willbreak existing WF 35 applications and urged that you put offdeveloping new WF-based applications if you havenrsquot beguncreating them already She also provided several tips for mini-

mizing the transition to the next version of WF In her opin-ion developers will win over the long run but she alsoacknowledges that the price to achieve these gains is steep

This monthrsquos Letters to the Editor include a response toDollardrsquos article from Matt Fritz Fritz laments the changes toWF as well as other similar types of changes that hersquos experi-enced as a Microsoft developer (see ldquoRunning the DevelopmentTreadmillrdquo p 8) Fritz notes that hersquos a strong believer in theMicrosoft development platformbut goes on to say that ldquousing[developers] as beta and field testers ainrsquot right It costs us andour companies time and moneyrdquo

Hersquos right These changes do carry a significant cost Theflip side of his argument is this Does Microsoft save Fritzmoney in the long run by making these changes The answeris It depends For some developers the changes will pay forthemselves handily over time for others the changes wonrsquotprovide the same returnwhether because the developer doesnrsquotneed the changes or because the changes mean abandoning aplatform or technology theyrsquove invested considerable timeand energy learning and deploying

One positive aspect of the changes to WF is that theyrsquoreoccurring before the product matured Another positiveaspect WF is not a technology thatrsquos in widespread use andthe current implementation is lacking in significant ways thatthe next version will address Therersquos a reason more peopledonrsquot use it now

But what if yoursquore one of those who made an investmentin the current version of WF Microsoft is consciously throw-ing away the efforts of the developers and companies it con-vinced to adopt this technology Itrsquos penalizing its own bestmost enthusiastic customersmdashthe people in fact who hadpaid money for WFWhen discussing Microsoftrsquos approach toWF with a couple advisors to VSM the conversation wouldusually start with ldquoBig Bad Microsoftrdquofor doing this to its cus-tomers but eventually would swing back to discussing why P

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

0209vsm_EdNote_6-8v5 12209 142 PM Page 6

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 9: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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 ESRIreg 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 yoursquore a desktop mobile server or Web developer EDN provides the

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

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

Subscribe to EDN and leverage the power of GIS to get

more from your data Visit wwwesricomedn

Project17 11909 524 PM Page 1

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 10: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

E D I T O R rsquo S N O T E gt gt C O S T O F C H A N G E

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom8

someone would put an immature or little-used technology towork in a mission-critical scenario

On the surface this argument strikes me as bizarre Arethe companies Microsoft convinces to use its technologies cul-pable when Microsoft changes things up You expect some riskwhen you use a beta or community technology preview tech-nology Maybe the same holds true for a version 1 productWeall know the adage that you shouldnrsquot adopt a pre-version 3product from Microsoft but we donrsquot actually mean it do weRegardless that argument shouldnrsquot be in play here Microsoftis scrapping a version 35 product The product hadnrsquotachieved maturity nor had it achieved widespread acceptancebut it seems unlikely you could see this coming if you were acompany that relied on WF

The changes that are occurring in WF wouldnrsquot seem sosignificant if there werenrsquot other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies For examplethe introduction of a NET version of VB roiled the VB com-munity for years and wersquore still feeling the aftershocks of someof those design decisions Microsoft was careful to note whenit introduced a NET version of VB that the existing codedevelopers had written would still work Similarly WF 35apps will continue to function But the blunt truth is Discon-tinuing a language or technology is a death sentence to futuredevelopment for that language or technology and even exist-ing applications face hardware and other limits on theirlongevity Sooner or later developers will have to move onwhether they want to or because they have to Even if existingapps continue to function or are maintained indefinitely yourability to earn a living with that tool or technology is severelylimited and you incur an opportunity cost when you need toabandon what yoursquore doing now for something else

Irsquom ambivalent about what constitutes the proper balancebetween maintaining backward compatibility and introducingnew features I want the software I use to provide features thathelp me do my job better and save me time over the long run Itshould also be noted that therersquos a cost to backward compati-bility especially in terms of application performanceAs muchas I hate to redo things or have to rework things to achieve functional equivalence Irsquom willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardmdashespecially whenthe reason for the change is compelling

But the central issue is this My notion of compellingdoesnrsquot always match that of the softwarersquos designers Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Officersquos ribbon anyone) It might be that acompany could change its product so it serves 95 percent of itsusers better but alienates me in the process I just donrsquot carehow much the first group wins if the software becomes unus-able for me Thatrsquos part of the equation that a company thatcreates software must considerWhen a company bets Irsquoll like afeature enough to not mind that it no longer works as it usedto that company places bets with my money as well as its ownAnd Irsquod like a company that places bets with my money to doso at least as conservatively as I would In the case of WFMicrosoft isnrsquot just betting with other peoplersquos money itrsquos say-ing the chips those early adopters bought from Microsoft cannever be redeemed A company ought to be extremely carefulabout making such bets because they represent a major with-drawal from the goodwill bank of their customers Doing thiseven once can be enough to turn a customer against you so achange that affects only one person in 20 can still have signifi-cant consequences If a company does this routinely itrsquos only amatter of time until it affects all its customers

What concerns me most about what occurred with WFare the implications these changes portend for the future forthose who use Microsoft technologies Today WF is a periph-eral technology There are people to whom itrsquos important butthere are other technologies such as Office Windows or evenVB that are not so peripheral For example Windows Com-munication Foundation is undergoing its own changes that Iunderstand will have anmdashadmittedly less dramaticmdasheffecton backward compatibility And Microsoft has announcedthat LINQ to SQL is basically shifting to something akin tomaintenance mode which is worrisome for many developerswho see it as their only workable data solution at themoment Sure I expect something else as yet unannouncedto take its place (Entity Framework) But how many timeswill you as a developer have to go through this process Moreto the point how long will you suffer Microsoft to put youthrough this VSM

Talk Back How do you go about striking the proper balancebetween backward compatibility and introducing new featuresin your own software Tell me at vsmedit1105mediacom orednote1105mediacom

The product hadnrsquot 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

0209vsm_EdNote_6-8v5 12209 142 PM Page 8

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 11: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Get tips Get codeGet the best how-to articles on the net

ONLINE

wwwvisualstudiomagazinecom

Project13 91807 334 PM Page 1

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 12: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom10

Letters to Visual Studio Magazine are welcome Letters must include yourname address and daytime phonenumber to be considered for publica-tion Letters might be edited for formfit and style Letters express the viewsof the individual authors and do notnecessarily reflect the views of theeditors VSM or 1105 Media Pleasesend them to Letters to the Editor coVisual Studio Magazine 230 CaliforniaSt San Francisco CA 94111 faxthem to 415-814-0961 or e-mailthem to vsmedit1105mediacom

Letters

Running the Development Treadmill

Kathleen Dollardrsquos article on the changes in the upcoming version of Workflow [AskKathleenldquoWindows Workflow Changes Directionrdquo January 2009] reminded me that thesame thing happened with SQL Server DTS 20002005 as well as with the MapPoint

object model and ADO Now SQL Notification Services was dropped in 2008 Are you kidding Itmakes you wonder How many times do you have to relearn things you used to know how to do

Irsquom a strong believer in the Microsoft developer platform and I believe the tools do getbetter over time But using us as beta and field testers ainrsquot right It costs us and our companiestime and money Now I have Biztalk Windows Communication Foundation WindowsWorkflow and LINQ on the ldquowait-and-seerdquo list with more to come no doubt If Microsoftstill believes that developers are the foundation of its business it needs to reconsider thisstrategy Gates himself talks about the great companies of yesteryear that couldnrsquot see whenthey started doing things wrong like DEC Wang and Novell (and now General Motors) Itrsquosa mistake to alienate the developer community Every company hasmdashor will havemdasha Toyotain the rearview mirror

Hey Bill Come back for awhile we need you to clean house Matt Fritz originally posted online

Examples Would Be NiceBill Wagnerrsquos article covering what VB developers should know about C would have beenmore useful if he had anchored the gee-whiz discussion of iterators lambdas and closureswith at least a mention of the closest approximation in VBNET functionality so that we couldhave gotten a clue as to what the differences are and why we should care [C Corner ldquoWhatVB Devs Should Know About Crdquo December 2008] As it is this read more like a ldquothings I liketo do in Crdquo article than an aid for folks trying to bridge the gap between VBNET and C

Bill Clardy Orange Calif originally posted online

CorrectionThe recent First Looks review of Compuwarersquos DevPartner Studio contained an error whendiscussing the capabilities of that toolrsquos Performance Analyzer [ldquoUnderstand What Your AppDoesrdquo January 2009] Performance Analyzer can be configured to analyze ASPNET applicationsrunning on both local and remote computers You can read an updated version of the reviewonline at VisualStudioMagazinecom that explains the general steps you need to take to usePerformance Analyzer with ASPNET Locator+ code VS0901FL

VSM regrets the error

VisualStudioMagazinecomFebruary 2009 bull Volume 19 bull No 2

Editorial StaffVice President Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor RMG

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 StaffCreative Director Scott Shultz

Graphic Designer Erin Horlacher

OnlineDigital MediaEditor VisualStudio Becky Nagel

MagazinecomExecutive Editor New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor Web Gladys Rama

Web Producer Shane Lee

Director Web Development Rita Zurcher

President Henry Allain

Vice President Publishing Matt N Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S Cook

Marketing Programs Manager Videssa Djucich

President amp Neal VitaleChief Executive Officer

Senior Vice President Richard Vitaleamp Chief Financial Officer

Executive Vice President Michael J Valenti

President 1105 Events Dick Blouin

Vice President Finance Christopher M Coatesamp Administration

Vice President Audience Abraham M LangerMarketing amp Web Operations

Vice President Information Erik A LindgrenTechnology amp Web Operations

Vice President Carmel McDonaghCirculation

Chairman of the Board Jeffrey S Klein

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

E-mail E-mail is routed to individualsrsquo desktops Please use thefollowing form FirstnameinitialLastname1105mediacom Do not include a middle name or middle initials

Telephone The switchboard is open weekdays 830 am to 530 pm Pacific time After 530 pm you will be directed to individual extensions

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

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

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

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

0209vsm_Letters_10v7 12209 137 PM Page 10

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 13: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

LooksFirstP R O D U C T L I S T I N G S + R E V I E W S

DDataDirect Connect for ADONETDataDirect Technologies has released DataDi-rect Connect for ADONET data providers WithDataDirect Connect for ADONET developerscan write and deploy NET enterprise appli-cations that connect to multiple databases including Oracle DB2 Microsoft SQL Server andSybase The latest product release includesnew provider features for each major databasenew performance-tuning options and intro-duces DataDirect Bulk Load a standards-basedimplementation of bulk-load functionality thatprovides a method for moving volume-intensedata across Oracle DB2 Microsoft SQL Serverand Sybase databases without having todeploy and load client libraries

The suite of ADONET data providers usesa 100 percent managed code architecturetherefore DataDirect Connect for ADONETeliminates the need for database clientlibraries Because managed code runs in theCommon Language Runtime (CLR) environ-ment it reduces risks and closes holes thatunmanaged code leaves exposed providingdevelopers with versatile deploymentoptions available in both application andclient-server environments With DataDirectConnect for ADONET developers get full sup-port for NET Framework

The latest release of DataDirect Connectfor ADONET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement cachinga connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to OracleDB2 and Sybase

DataDirect Connect for ADONET List amp Label 14 and MobileForms Toolkit 2009

DataDirect Connect for ADONET now sup-ports Oracle 11g R2 SQL Server 2008 andDB2 iSeries V6R1 A complete list of databaseprovider features is available online

DataDirect Connect for ADONET

DataDirect Technologies

Price Contact vendor for pricing

Web wwwdatadirectcom

Phone US 800-876-3101

World 44 (0) 1753 218 930

List amp Label 14Combit has released version 14 of its report-generating software List amp Label Among thenew features is the inclusion ofa real-data-preview so changescan now be seen with real datawithout having to leave theDesigner Within the previewtherersquos also an integrated indexto ease navigation through thereport Additionally itrsquos nowpossible to mix different for-mats within the same docu-ment Now multiple formats arepossible as well as the choice ofprinter type Using a singlerecord from the database theuser can define real rows thatcan be represented in a line diagram withrespect to time

Also new for Professional and Enterprise Edi-tion 14 is the generation of DOM code DOMcode is now automatically provided by the Listamp Label object model directly from the projectfile The DOM viewer has been completelyreworked and now includes a search utility for

objects and properties Besides functions andobjects the user can now create their owndesigner actions with DOM and Designer Newwith version 14 is support for Delphi 2009Additionally the project parameter interfacehas been extended with a method and allowsthe storage of SQL queries or even completedata sets within a project

Other additions in version 14 include anextended formula assistant better overview ofproperty values magnetized help lines in theDesigner and your own Designer actions

With List amp Label software developers canequip their own applications with functions toassist in the generation of reports statistics

forms lists and labels Only a few lines of codeare required to integrate the report generatorinto existing applications The Designer whichcan be passed on to end users without havingto pay additional license fees is available in 15languages The development tool for reportingfunctions as well as Web reporting is availablein German or English and can process almost all

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 11

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 11

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 14: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

character sets All three editions of List amp Label can be integrated into alarge variety of programming languages

List amp Label 14

Combit GmbH

Price Standard Edition is available for 370 euro Subscription Editions Profes-

sional starts at 1380 euro and Enterprise at 2094 euro

Web wwwcombitneten

Phone +49 (0) 7531 90 60 10

MobileForms Toolkit 2009Resco has released an updated suite of controls and libraries for NETCompact Framework (CF) developers targeting Pocket PCs smart-phones and Windows CE NET devices The new suite MobileFormsToolkit 2009 is optimized for Microsoft Visual Studio 2008 andMicrosoft NET CF 35 Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interfaceAdding Touch functionality to mobile applications is a simple matter ofsetting up a single property in Microsoft Visual Studio

MobileForms Toolkit 2009 includes many controls and libraries thattackle most of the common problems that developers encounter devel-oping for the mobile environment Tools include SmartGridmdasha grid con-trol with built-in auto edit capabilities Touch scroll support and theability to save different SmartGrid layouts to XML files AdvancedListmdasha professional list control suitable for small displays of mobile devicesand includes DelayLoad functionality that loads only visible data forfast previews while additional data is loaded on demand Com-pactChartmdasha charting control with five chart types including Pie BarLine Doughnut and Area charts OutlookWeekCalendar and Outlook-MonthCalendarmdashdayweek and monthyear appointment schedulingcontrols OutlookDateTimePickermdasha modern version of a common con-trol providing advanced styles DetailViewmdashfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel InkBoxmdashan ink control suitable for quick notes or signatures ImageBoxmdashanimage control supporting various graphic formats CustomKeyboardmdashaflexible control supporting custom keyboard layouts OutlookShortcut-Barmdasha popular shortcut control common for all modern applications alibrary for playing and recording audio and more

For more information about the Resco MobileForms Toolkit 2009 anda complete list of controls and libraries visit httptinyurlcom9wukrz

MobileForms Toolkit 2009

Resco

Price Standard Edition $49995 Professional Edition $99995

Enterprise Edition $199995

Web wwwresconet

Fax +421 2 090 2010

Editorrsquos Note Please send product information to New Products Editor co

Visual Studio Magazine 230 California St San Francisco CA 94111 Phone

415-814-0950 fax 415-814-0961 e-mail vsmedit1105mediacom

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

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

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

API supports NET C++ Java databases etc New NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrievalreg

since 1991

1-800-IT-FINDS bull wwwdtsearchcom

ldquoBottom line dtSearch manages a terabyte of text in a single index and returns results in less than a secondrdquo ndash InfoWorld

ldquoFor combing through large amounts of datardquo dtSearch ldquoleads the marketrdquo ndash Network Computing

dtSearch ldquocovers all data sources powerful Web-based enginesrdquo ndash eWEEK

dtSearch ldquosearches at blazing speedsrdquo ndash Computer Reseller News Test Center

See wwwdtsearchcom for hundreds more reviews and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CDDVDsPublish for CDDVDsPublish for CDDVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win amp NETEngine for Win amp NETEngine for Win amp NET

New64-bitNew64-bit

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 12

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 15: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 13

MMadCap Flare 41 is a professional development environ-ment for creating documentation for a wide range of formats based on a single-source (XML) As a program-ming writer I was struck by how Flare offers so manymust-have features of Visual Studio to technical writers

Information developers have much in common withsoftware developers They want to work in a familiarintegrated environment that organizes files flagserrors assists with testing and reporting controls thebuild process and generally makes them more efficientFlare does all this and more For example it takes a cuefrom software development by allowing projects to linkto common content As with pre-built software compo-nents you can store and update shared pagesmdashforexample legal disclaimersmdashin one place All of the projects and documentation suites can incorporate thelatest version into the build automatically

IntelliSense an essential feature for writing code isnow available in documentation projects As you writeinstructions the IDE suggests phrases that appear inthe projectrsquos topics Likewise you can drag snippetsand drop them directly into a topic

To accommodate Windows Presentation Foundation (WPF)and Silverlight software projects Flare now supports an array ofvector graphic types including the XAML format A nice touch isthe ability to convert those images automatically to Web-safeformats such as GIF or JPG for browser-hosted output Speakingof formats Madcap creates PDF and XPS files directly withoutrequiring Microsoft Word Adobe FrameMaker or Adobe Acrobatas intermediaries Unfortunately MadCap still doesnrsquot generatefiles that integrate with Visual Studiorsquos help collections (MS

Help 2) Another valuable output would be XAML markup for Silverlight apps

Source control is essential for programmers and writers alikeWhen you create a Flare project therersquos a checkbox to bind to asource control provider including Visual SourceSafe TeamFoundation Server and a generic plug-in The Bind Projectoption recognized and connected to my SourceGear Vaultprovidermdasha real bonus That said the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option

Yoursquoll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium Forexample in a PDF you might generate ldquoas shown on p 32rdquowhere the HTML version which doesnrsquot use page numberswould substitute a hyperlink

MadCaprsquos user assistance is polished and plentiful The Get-ting Started Wizard sample projects videos dynamic help andhelp topics get you up to speed and over the hurdles

On the downside Flare sets off your firewall alarm as itaccesses the network to validate your license key usage andthe software stops working until youmdashor the IT departmentmdashunblock its stealth access With product announcements thatstart with ldquoDear Propeller Headsrdquo the folks at MadCap seemfriendly fun and upfront Thatrsquos why a high-handed licensingapproach is disappointing and out of character VSM

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

ldquoASPNET 35 for Dummiesrdquo (For Dummies 2008)

REDUCE KEYSTROKES AND WRITERrsquoS CRAMP You can store frequently used resources as snippets in MadCap Flare 41 Justdrag-and-drop the content into the editor For larger files you canlink to complete boilerplate topics from a central location

AT A GLANCE

MadCap Flare 41MadCap SoftwareWeb wwwmadcapsoftwarecomPhone 858-320-0387Price $899Quick Facts Integrated development environmentfor authoring user manuals online help and Webpages Generates multiple output formats from a single XML sourcePros File linking and conditional text XML editorIntelliSense support drag-and-drop snippets source-control friendly command-line mode built-in PDFand XPS generators valuable user assistanceCons Doesnrsquot generate integrated help for VisualStudio help collections sets off firewall alarm to validate license key

Develop Help Content Like a Professional

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

0209vsm_FirstLooks_11-13v7 12209 139 PM Page 13

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 16: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom14

cloud computing Microsoftrsquos cloud candidatemdashWindows Azuremdashoccupied the bulk of OzziersquosDay One PDC keynote and was the subject of 39sessions more than twice as many as the next-most-discussed topicmdashVisual Studio WindowsAzure is an Internet-facing operating system thatpromises to enable NET developers to leveragetheir current ASPNETWindows CommunicationFoundation (WCF)and Windows Workflow pro-gramming skills to deploy NET Web applicationsto Microsoftrsquos newly built data centers quickly andeasily Microsoftrsquos message to VS developers is toldquouse your existing tools knowledge and skill setrdquofor projects you deploy to Windows Azure

The Azure Services Platform for which theWindows Azure OS serves as the foundationprovides ldquomassively scalablerdquotable and blob storageservices a persistent message-queue service sev-eral NET utility services (formerly code-namedldquoZurichrdquo) a Live operating environment and thesuccessor to SQL Server Data Services thatrsquos nowcalled SQL Data Services (see Figure 1 oppositepage) Irsquoll give you a brief introduction to theplatformrsquos objectives and its architectural detailsto achieve them and describe how Azure differsfrom its cloud-based competitors Then Irsquoll drilldown into programming data-intensive Webapplications that take advantage of Azurersquos

The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development team

the opportunity to play catch-up with Amazoncom Inc Google Incand other major players in the race to capture developer mindshare for

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

TECHNOLOGY TOOLBOX

F E AT U R E

Visual Studio 2008 ASPNET and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centersThe result You get maximized availability and reliability withalmost limitless on-demand scalability while you pay only forresources consumed BY ROGER JENNINGS

Retire Your Data Center

VBNET

C

SQL Server

ASPNET

XML

Other Azure ServicesPlatformElastic ComputeCloud (EC2)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 14

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 17: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 15

ILLU

ST

RA

TIO

N B

Y R

AN

DY

LY

HU

S

unique development and deployment tools Finally Irsquoll discuss aninstrumented ASPNET test harness for Azure Table Services that youcan download run locally with the community technology preview(CTP) of the Windows Azure SDK and then deploy to the WindowsAzure CTP running in a Microsoft data center (see the Go Onlineinformation on p 25 for details) Future VSM issues will cover BlobServicesQueue ServicesSQL Data Services and NET Services

ldquoCloud computingrdquo is a catch-all term for Web-based utility computing operations provisioned aspay-by-usage software services and accessed over theInternet Amazon Web Services and Google AppEngine are probably the best-known cloud-computingservices but Web-hosting firms such as RackspaceHosting Inc and specialty vertical-market providerslike SalesForcecom Inc also fit into the cloud-comput-ing picture The primary economic justification formoving data center activity to the cloud is avoidance ofcapital expenditure for servers and associated net-working hardware to handle peak instead of averageloads Other benefits include reduction of IT manage-ment and operating costs improved application relia-bility and availability and the ability to scale Webapplications up-and-out quickly to match rapidincreases in traffic When the traffic subsides such asafter holiday sales resources can return to the poolautomatically or by manual intervention Clouddeployment also offers a rapid method for provingWeb application or service concepts without makinginfrastructure investments

Azure Echoes AWSAzurersquos architecture most closely resembles a combi-nation of Amazon Web Services (AWS) Elastic Com-pute Cloud (EC2) running Windows Server 2003 R2with SimpleDB for semi-structured tables SimpleStorage Service (S3) for blob storage Simple QueueService (SQS) for messaging between applicationsand Elastic Block Store to persist other instance data(see Table 1 p 23 and Additional Resources p 25)Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage as is the Google AppEngine (GAE) Microsoft wonrsquot reveal pricing forAzure services until later in 2009 when version 1 is

closer to release However the current word is that Azure will beldquocompetitiverdquo presumably with the AWS GAE or both pricelists and the Service Level Agreement will be factored intomonthly charges Itrsquos not known whether Microsoft will adoptGooglersquos approach of billing only for App Engine usage in excess of fixed quotas for free CPU time network ingress and egressand storage

FIGURE 1 Move ASPNET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system which provides the fabricfor virtualized Windows 2008 Server instances schemaless persistent table bloband queue storage NET Services for managing authentication authorization inter-service communication and workflows and SQL Services for data management withrelational database features and consumer-oriented Live services Like the GoogleApp Engine Azure provides a development environment that emulates its cloudoperating system and storage services

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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 15

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 18: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom16

Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsoftrsquos Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing datareplication and resource management According to MicrosoftrsquosErick Smith the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines load balancersrouters and switches it manages in a Microsoft data center Edgesof the graph are interconnections of various types for examplenetwork serial and power cables You specify the topology ofyour servicemdashthe number and connectivity of roles the attrib-utes and locations of the various hardware components as wellas the numbers of faultupdate domains and maximuminstances of each role you need with a declarative Service ModelIn this respect Windows Azure management features are similarto those offered by RightScale for AWS and employed by theGAE Roles are runnable components of an application roleinstances run on the fabricrsquos nodes and channels connect roles

The CTP limits applications to managed code authored in VS2008 that runs under a custom version of medium trust CodeAccess Security Microsoft promises future support for PythonRuby native code and Eclipse Fault domains for role instancesrepresent a single point of failure such as a rack update domainsfor performing rolling software upgrades or patches run across mul-tiple fault domains (see Figure 2)Ultimatelyyoursquoll be able to specifyyour Service Model with Oslorsquos domain-specific language tools andstore the model in the Oslo repository

The current CTP released at PDC 2008 doesnrsquot expose theService Model instead the Windows Azure Tools for MicrosoftVisual Studio add-in defines common Azure application-roletemplates for Web Role Worker Role and Workflow The WebRole enables creating a new Web Cloud Service or Web andWorker Cloud Service as an ASPNET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3opposite page) Windows Azure doesnrsquot support file-system Web

site projects Worker Roles are asynchronous oper-ations that perform background processing whenadded to Web projects roles also can create stand-alone Worker Cloud Services The most commonuse for Worker Roles is processing messages addedto an Azure Queue Workflows enable writingstandalone CloudSequentialWorkflow projects orcan be incorporated in Web or Worker Cloud Ser-vices Azurersquos October 2008 CTP limits testers to amaximum of 2000 runtime hours with up to eightinstances of a single production application hav-ing one Web and optionally one Worker Role

Emulate the Cloud LocallyAzure was in a limited (private) beta stage at presstime You can apply for admission to the Azure Ser-vices Platform beta program at the Microsoft Con-nect site the OakLeaf blog offers a walkthrough ofthe somewhat convoluted sign-up process (seeAdditional Resources p 25) However you donrsquotneed to wait for a beta invitation because down-loading and installing the Windows Azure SDK(October 2008 CTP) and Windows Azure Tools forMicrosoft Visual Studio (October 2008 CTP) letsyou emulate the Azure Services Platform on yourlocal development machine Installing the SDKadds a start menu folder with Development Fabricand Development Storage nodes as well as ReleaseNotes Windows Azure SDK Command Promptand Windows Azure SDK Documentation nodesChoosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbarrsquos Notification Area opens managementdialogs for the two service emulators (see Figure 4p 18)

When you specify one of the Cloud Servicestemplates (typically a Web Cloud Service) for a

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to supportapplication instances on multiple fault domains (server racks) to prevent a singlepoint of failure Instances run on nodes which usually are virtualized Windows2008 Servers but can be physical machines Azure currently maintains a masterand two replicas of application roles XCopy application deployment simplifiesadding new or upgrading applications Rolling upgrades or service releases onlyaffect a single update domain at a time to prevent application downtime UnlikeAmazon and Google services Azure offers an intermediate Staging deploymentfor new apps that developers can test with a private URL then deploy to theaccountrsquos public Production URL (see Figure 6 p 22)

0209vsm_F1Retire_14-25v13 12209 141 PM Page 16

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 19: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 17

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

new VS 2008 project the add-in generates a solution with aCloud Service project which contains ServiceCon-figurationcscfg and ServiceDefinitioncsdef files as well as anASPNET Web Role application You also must expand the Win-dows Azure SDKrsquos Program FilesWindows Azure SDKv10sam-pleszip file to a temporary folder Then add the TempStorage-Client LibStorageClientcsproj and TempHelloFabricCom-monCommoncsproj projects to your solution by right-clickingon the solution in Solution Explorer and selecting Add an ExistingProject Add the two project files as references toyour ProjectName_WebRole application TheStorageClient library delivers wrapper classes forREST API operations on Azure Blob Queue andTable Services the Common library providesApplicationEnvironment classes for logging andother local fabric-related activities The AzureTools add a reference to MicrosoftServiceHost-ingServiceRuntimedll for the local fabric auto-matically Right-click on the Cloud Service proj-ect node and choose Create Test Storage Tables toadd ProjectName tables to your local instance ofSQL Server 2005+ Express At this point you canimport page and class files for existing ASPNETprojects or create a new Web application fromscratch

Settings in the ServiceConfigurationcscfg filedetermine whether your application uses local orcloud storage when emulating the hosted serviceHerersquos a ServiceConfigurationcsfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated

ltxml version=10gtltServiceConfiguration

serviceName=SampleWebCloudService xmlns=httpschemasmicrosoftcom ServiceHosting200810ServiceConfigurationgt

ltRole name=WebRolegtltInstances count=3gtltConfigurationSettingsgtltSetting name=AccountName

value=devstoreaccount1gtltSetting name=AccountSharedKey

value=Eby8vd hellip MGw==gtltSetting name=BlobStorageEndpoint

value=http12700110000gtltSetting name=QueueStorageEndpoint

value=http127001100001gtltSetting name=TableStorageEndpoint

value=http12700110002gtlt-- ltSetting name=AccountName

value=ltyouraccountnamegtgt

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

FIGURE 3 Choose a Pre-configured Cloud Service Role or Workflow The October 2008 community technology previewrsquos Windows Azure Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service WorkerCloud 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 ServiceConfigurationcscfg and ServiceDefinitioncsdef files and a pointer to aProjectName_WebRole project as shown for this articlersquos SampleWebCloudServiceproject in Solution Explorer Common and StorageClient class libraries provide locallogging features and wrapper classes for Azure Storage Servicesrsquo REST API TheLimog class contains code to regenerate the CustomerTable

0209vsm_F1Retire_14-25v13 12209 141 PM Page 17

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 20: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom18

ltSetting name=AccountSharedKey value=ltYourPrimaryAccessKeygt gt

ltSetting name=BlobStorageEndpoint value=httpblobcorewindowsnet gt

ltSetting name=QueueStorageEndpoint value=httpqueuecorewindowsnet gt

ltSetting name=TableStorageEndpoint value=httptablecorewindowsnet gt --gt

ltConfigurationSettingsgtltRolegt

ltServiceConfigurationgt

Settings for cloud storage services are commented out in the preceding example local setting values are the same for all usersThe ltInstances count=3gt element causes three instances to run in the Development or Azure Fabric Note that the preced-

ing 127001 (localhost) port numbers appear in Figure 4rsquosDevelopment Storage dialog YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalrsquosProject Summary page

Each ltSetting name=Endpoint hellip gt element in the Ser-viceConfigurationcsfg file must have a corresponding entry in theServiceDefinitioncsdef file (indicated here in red)

ltxml version=10 encoding=utf-8gtltServiceDefinition name=SampleWebCloudService

xmlns=httpschemasmicrosoftcomServiceHosting200810ServiceDefinitiongt

ltWebRole name=WebRolegtltInputEndpointsgtlt-- Must use port 80 for http and port 443 for

https when running in the cloud --gtltInputEndpoint name=HttpIn

protocol=http port=80 gt

ltInputEndpointsgtltConfigurationSettingsgtltSetting name=AccountNamegtltSetting name=AccountSharedKeygtltSetting name=BlobStorageEndpointgtltSetting name=QueueStorageEndpointgtltSetting name=TableStorageEndpointgt

ltConfigurationSettingsgtltWebRolegt

ltServiceDefinitiongt

If the ltSettinggt element name attribute values donrsquotmatch in the two files you receive an ldquoInvalid configu-ration filerdquo message when running in the DeveloperFabric the Azure Fabric adds the names of missing ormisspelled ltConfigurationSettingsgt elements Thematching ltSettinggt name attributes requirement ishidden in an ldquoIssues and Constraints in the WindowsAzure Tools and SDKrdquo white paper (see AdditionalResources p 25) The ltInputEndpointgt elementrsquosport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSmdashSecure Sock-ets Layer (SSL)mdashprotocol Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodersquos properties sheet

Connect to Schemaless EAV Tables with RESTWindows Azure tables are similar to the schemalessEntity-Attribute-Value (EAV) tables of the initial SQL

Azure tables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tables are

designed to scale to billions of entities and terabytes of data

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multipleexposure screen capture shows log data for three instances of this articlersquos SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs queues and Azurersquos schemaless Entry-Attribute-Value tables A local SQL Server 2005+ Express instance holds a Develop-mentStorageDb database to store blobs queues and account information as well as a ProjectName database containing Azure Table Services data Startingup the Development Fabric and Development Services slows VSrsquos compile andrun operations significantly

0209vsm_F1Retire_14-25v13 12209 141 PM Page 18

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 21: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 19

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

Server Data Services (SSDS) CTPrsquos Authority-Container-Entity (ACE) model which has been incorporatedinto Windows Azure as SQL Data Services (SDS)

The EAV data model is much more scalable thanconventional file system-based relational tables Azuretables have a distributed architecture thatrsquos related to Googlersquos Bigtable and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data Azure and SDS table versions offerfree-form ldquoopen propertiesrdquo (formerly ldquoflex proper-tiesrdquo) or property bags and permit adding or remov-ing table attributevalue pairs at will However thetwo versions have different required properties andsets of data types

Azure tables require PartitionKey and RowKeystring property values to form a concatenated primarykey and automatically add a DateTime Timestampproperty value to each entity SDS entities require aunique Id property value permit an optional Kindproperty and supply an autoincrementing Versionvalue for concurrency management

Azure tables support Binary Bool DateTimeDouble GUID Int Long and String data types SDSoffers Base64Binary Blob Boolean DateTime Deci-mal and String data types SimpleDB property valuesare limited to strings and require padding numberswith leading zeros and adding offsets for negative val-ues which complicates client programming MyldquoComparing Google App Engine Amazon SimpleDBand Microsoft SQL Server Data Servicesrdquo blog postprovides a detailed comparison of those three services(see Additional Resources p 25)

Azure tables and SDS containers are units of consistencyand have a size limit of 2GB SimpleDB domains which corre-spond approximately to Azure tables hold a maximum of 10GBAzure tables and SDS containers have strong consistency allobservers see the same value immediately after an update specialalgorithms guarantee consistency over multiple replicas Sim-pleDB domains promise eventual consistency after a period withno new updates but Amazon doesnrsquot specify the inconsistentwindowrsquos maximum duration

Transactions are crucial for online order processing andother business applications but neither Azure nor SimpleDBtables currently support transactions However the Azure teampromises that their tables will ldquoat some point in the future per-form atomic transactions across multiple entities within thesame partitionrdquo Partitions are similar to Bigtablersquos tablets withsome characteristics of the App Enginersquos entity groups thrownin a single VM or server stores all entities in the table with thesame PartitionKey value (App Engine offers transactions forentities in the same Entity Group) The CTP provides equalityfilters only and sorts in PartitionKeyRowKey order inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version

Progress Toward StandardsMicrosoftrsquos data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid paceAzure tables blobs and queues have a REST API while SDS andSimpleDB provide REST and SOAP protocols

Azure tables and SDS use a new version of the ADONETData Services (ldquoAstoriardquo) runtime which supports ldquoopen prop-ertiesrdquo with the Atom syndication wire protocol and operateswith the existing ADONET Data Services client libraries andtools Pablo Castrorsquos ldquoADONET Data Services in WindowsAzure pushing scalability to the next levelrdquo blog post describeshow the Astoria team modified the runtime to accommodate adynamic ldquoopen propertiesrdquo provider for Azure and SDS in addi-tion to the static CLR types defined by the more common EntityFramework and LINQ to SQL data providers (see AdditionalResources p 25)

The REST API for Azure defines HTTP GET (query) POST(create) PUT (update with properties replaced) MERGE (updatewithout properties replaced) and DELETE operations on entitiesHerersquos the GET request header for the second page of the sampleprojectrsquos Customers GridView which starts with CENTC as theCustomerID and RowKey value

FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azurersquos ldquoClick-Twicerdquo deployment approach lets you test your project ina Staging instance with a private guidcloudappnet URL before placing it in pro-duction with your AccountNamecloudappnet URL Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectNamecspkg package and ServiceConfigurationcscfg files inthe projectrsquos hellipProjectNamebinDebugPublish folder Clicking OK exposes theHosted Service page with the Staging instance in Allocated mode Click Run tostart the staged service test it with the private URL click Suspend and thenclick the exchange icon to place it in production

0209vsm_F1Retire_14-25v13 12209 141 PM Page 19

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 22: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Project1 12109 1114 AM Page 1

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 23: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Project1 12109 1115 AM Page 2

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 24: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

GET CustomerTable()$top=12ampNextPartitionKey=CustomerampNextRowKey=CENTC HTTP11

User-Agent Microsoft ADONET Data Servicesx-ms-date Fri 19 Dec 2008 233731 GMTAuthorization SharedKeyLite oakleafZKA hellip 5Yc=Accept applicationatom+xmlapplicationxmlAccept-Charset UTF-8DataServiceVersion 10NetFxMaxDataServiceVersion 10NetFxHost oakleaftablecorewindowsnet

Azure Table and Queue Services require authentication as doprivate Blob Services blobs are the only storage type that can bespecified for public access The Authorization headerrsquos Shared-KeyLite value shown abbreviated in the preceding request head-er is specific to the Astoria client and is the HMAC-SHA256encoding of this string

Fri 19 Dec 2008 233731 GMTnoakleafTables

Queries return a maximum of 1000 entities and support the

$top operator The Atom-formatted response body includes x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey continuation tokens to identify the first entity ofthe next page Optimistic concurrency management uses eTagsand Timestamp values to detect conflicts with If-Match HTTPheaders Herersquos the GET response header and abbreviated bodyof the second GridView page

HTTP11 200 OKCache-Control no-cacheContent-Type applicationatom+xmlcharset=utf-8Server Table Service Version 10 Microsoft-

HTTPAPI20x-ms-request-id 2a109a5d- hellip f6ex-ms-continuation-NextPartitionKey Customerx-ms-continuation-NextRowKey FRANKDate Fri 19 Dec 2008 233700 GMTContent-Length 15691

ltxml version=10 encoding=utf-8 standalone=yesgt

ltfeed xmlbase=httpoakleaftablecorewindowsnet

xmlnsd=httpschemasmicrosoftcomado200708dataservices

xmlnsm=httpschemasmicrosoftcomado200708dataservicesmetadata

xmlns=httpwwww3org2005Atomgtlttitle type=textgtCustomerTablelttitlegtltidgthttpoakleaftablecorewindowsnet

CustomerTableltidgtltupdatedgt2008-12-19T233701Zltupdatedgtltlink rel=self title=CustomerTable

href=CustomerTable gtltentry metag=Wampquotdatetime2008-12-

9T223A103A302752Zampquotgtltidgthttpoakleaftablecorewindowsnet

CustomerTable(PartitionKey=CustomerRowKey=CENTC)

ltidgtlttitle type=textgtlttitlegtltupdatedgt2008-12-19T233701Zltupdatedgtltauthorgtltname gt

ltauthorgtltlink rel=edit title=CustomerTable

href=CustomerTable(PartitionKey=CustomerRowKey=CENTC) gt

ltcategory term=oakleafCustomerTable scheme=httpschemasmicrosoftcom

ado200708dataservicesscheme gt

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

FIGURE 6 Try the Live Table Services Sample Project You can run this articlersquosSampleCloudWebServicesln project in the Azure Services Platform CTP atoakleafcloudappnet The Defaultaspx page contains a paged GridView thatdisplays 12 Northwind Customers records per page and a FormView forinserting new entities both controls are bound to an ObjectDataSource thatconnects to an Azure table (The projectrsquos FormView is disabled in the publicversion) The Count button iterates the entity set clicking on Delete All Customers deletes the table and Create Customers recreates the table andadds Customer entities Update Customers toggle the addition or deletion ofa plus sign (+) after the CompanyName The Time textbox displays theelapsed time of the server components of these operations

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom22

0209vsm_F1Retire_14-25v13 12209 141 PM Page 22

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 25: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 23

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

ltcontent type=applicationxmlgtltmpropertiesgtltdPartitionKeygtCustomerltdPartitionKeygtltdRowKeygtCENTCltdRowKeygtltdTimestamp mtype=EdmDateTimegt2008-12-19T2210302752Z

ltdTimestampgtltdAddressgtSierras de Granada 9993

ltdAddressgtltdCitygtMeacutexico DFltdCitygtltdCompanyNamegt

Centro comercial MoctezumaltdCompanyNamegtltdContactNamegtFrancisco Chang

ltdContactNamegthellip

ltmpropertiesgtltcontentgt

ltentrygtltfeedgt

Use LINQ to REST to Query TablesADONET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries which an expressiontree translates to an HTTP URI The StorageClient libraryrsquosTableStorage TableStorageDataServiceContext and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADONET Data Services clientlibrary (SystemDataServicesClient) and implement Azure TableServices helper functions for CRUD operation on tables authen-tication and error handling

You define a TableName DataModel type that implementsTableStorageEntity and a TableName DataServiceContext thatinherits from TableName DataServiceContext Next you instanti-ate the latter in the PagePreload event handler with a StorageAc-countInfo type as its parameter and create and execute a LINQ toREST query with optional paging as shown here for the sampleproject

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 15 - 17 GHz x64 equivalent 17GHz

Memory 17GB 175GB

Network 100Mbps 250Mbps

Transient storage 250GB 160GB

Persistent storage 50GB Azure storage (maximum for CTP) Elastic Block Store (up to 1TB)

AuthenticationAuthorization

NET Access Control LiveID username pass-word X509 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 Amazoncom Incannounced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003 The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS NET 20 SP1 30 SP1 and 35 (not SP1) and SQL Server Express 2005 TheAzure 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 CTPinstance and Amazon EC2 beta default instances

Windows Azure management features are similar to those offered by RightScale for AWS and employed

by the Google App Engine

0209vsm_F1Retire_14-25v13 12209 141 PM Page 23

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 26: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom24

protected void Page_Prerender(object sender EventArgs e)

This LINQ to REST query gets a page of 12 Customer entities at a time From paging code by Microsoftrsquos Steve Marx

var query = (DataServiceQueryltCustomerDataModelgt)(new CustomerDataServiceContext(account)CustomerTableTake(12))

Get the continuation tokens from the requestvar cTokens = Request[ct]if (cTokens = null)

ct parameter format is ltpartitiongtltrowgtstring[] tokens = cTokensSplit()var partitionToken = tokens[0]var rowToken = tokens[1]

These QueryOptions become continuation token query parameters in the requestquery = queryAddQueryOption(

NextPartitionKey partitionToken)AddQueryOption(NextRowKey rowToken)

Execute the LINQ to REST queryvar result = queryExecute()

Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result

Get the continuation token valuesstring nextPartition = nullstring nextRow = nullqorHeadersTryGetValue(

x-ms-continuation-NextPartitionKey out nextPartition)

qorHeadersTryGetValue(x-ms-continuation-NextRowKey out nextRow)

if (nextPartition = null ampamp nextRow = null)

Add the continuation tokens to the GET querynextLinkNavigateUrl =

stringFormat(ct=01 nextPartition nextRow)

Set the customersView DataViews DataSource to the query resultcustomersViewDataSourceID = nullcustomersViewDataSource = resultcustomersViewDataBind()

Yoursquoll also need code like this that runs once for each session in theGlobalasaxcs file to create the initial table from your TableNameDataModel class

StorageAccountInfo account = StorageAccountInfo

GetDefaultTableStorageAccountFromConfiguration()TableStorageCreateTablesFromModel

(typeof(CustomerDataServiceContext) account)

After debugging your project in the SDKrsquos local Developer fabriccopy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodersquos Properties sheetright-click on the node and choose Publish to open a windowcontaining your projectrsquos hellipbinDebugPublish folder Click onDeploy in the Manage pagersquos Staging area to open the StagingDeployment page browse to the ProjectNamecspkg and Service-Configurationcscfg files to fill the App Package and Configura-tion Settings text boxes add a unique name (label) for the projectto the Properties text box and click on Deploy to copy the pack-age and configuration data to a Staging instance (see Figure 5p 19) After you test the role with the private Web site URL clickon the central icon to move the project to Production status andtest it with your public accountnamecloudappnet URL (see Fig-ure 6 p 22)ldquoClickTwicerdquo (once for Staging once for Production)deployment of roles to the Azure Fabric is a snapmdashand much eas-ier than migrating apps to AWS or the GAE

SDS vs AzureTherersquos considerable overlap of Azure Table Services and SDS fea-tures which portends a future conflict at least as serious as thatbetween LINQ to SQL and the Entity Framework A SQL

Therersquos 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

0209vsm_F1Retire_14-25v13 12209 141 PM Page 24

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 27: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 25

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

Services Labs incubation project is in the works to align SDS withthe ADONET Data Services and enable Atom and JavaScriptObject Notation (JSON) as wire protocols The SDS team intendsto add more relational-style features to the SDS data model in the future

According to Microsoft partner architect Gopal KakivayaldquoAmong the things SQL Data Services will include in the futureare improvements in backup and restore differential b-trees dis-tributed transactions geo-replication (synchronous and asyn-chronous) distributed materialized views job framework anddistributed queriesrdquo

The SDS team has promised for months to support schemasand full-text search in later CTPs SDS probably will become apremium offering with a substantial surcharge over basic AzureTable Storage For example Amazon extracts a $060 to $120 perinstance-hour surcharge for SQL Server 2005 Standard (SQLServer 2005 Express comes free with the $0125 to $120 hourlycharge for Windows Server 2003 R2 instances) Amazonrsquos sur-charge for Windows Authentication Services is $025 to $060 perinstance-hour depending on instance type That totals $7344 to$15552 extra per instance-year Windows Azure with Azure TableStorage probably will be the price leader that entices enterprisesto give Azure Platform Services a serious shot at playing a signifi-cant role in their data center expansion plansVSM

Roger Jennings is an independent data-oriented NET developer andcomputer book author with more than 125 million English copies inprint His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages Jenningsrsquos latestbook is ldquoProfessional ADONET 35 with LINQ and the EntityFrameworkrdquo (WROXWiley 2009) Hersquos also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News andmanages the OakLeaf Systems blog (oakleafblogblogspotcom) Youcan reach him at Roger_Jenningscompuservecom

ADDITIONAL RESOURCES

Azure Services Platform homepage tinyurlcom6lr5nr

MSDN homepage for Azure developers tinyurlcom65ogcw

Windows Azure SDK (October 2008 CTP) download tinyurlcom5pha33

Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download tinyurlcom58oega

Azure Services Training Kit - PDC Preview download tinyurlcom5z87ru

Register with Microsoft Connect to access Azure services onlinetinyurlcom5urpnv

ldquoSetting Up the Windows Azure Services Platform An Illustrated Walk-throughrdquo OakLeaf blog post tinyurlcom65wywn

Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9) tinyurlcom5tsgvm transcript tinyurlcom5vhprm

Video clips of 39 Azure-related sessions at PDC 2008 (Channel9)tinyurlcom5vd7cr

Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9) tinyurlcom638uoo

Azure SDK online documentation tinyurlcom6yy75b

SQL Services Labs home page with planned ldquoincubationrdquo projects for SDStinyurlcom5asfdm

ldquoWindows Azure TablesmdashProgramming Table Storagerdquo white papertinyurlcom59tlo7

ldquoWindows Azure TablesmdashProgramming Blog Storagerdquo white papertinyurlcom6785ra

ldquoIssues and Constraints in the Windows Azure Tools and SDKrdquo whitepaper tinyurlcom4m92h9

The Atom Syndication Format (10) specification (IETF RFC 4287)tinyurlcomysewpe

ldquoAmazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta)rdquo data sheet tinyurlcom4xw9cw

ldquoAmazon Elastic Compute Cloud (Amazon EC2)rdquo data sheethttptinyurlcom4bw86s

ldquoADONET Data Services in Windows Azure pushing scalability to the nextlevelrdquo blog post by Pablo Castro tinyurlcom4ky4x2

ldquoComparing Google App Engine Amazon SimpleDB and Microsoft SQLServer Data Servicesrdquo OakLeaf Systems blog post tinyurlcom626td8

ldquoTest Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformancerdquo OakLeaf Systems blog post httptinyurlcom5ea99x

ldquoSQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platformrdquo OakLeaf Systems blog post tinyurlcom58tw7c

ldquoTest-Drive SQL Server Data Servicesrdquo by Roger Jennings Locator+ CodeVS0807RJ_T

ldquoManipulate Data in the Cloudrdquo by Roger Jennings Locator+ CodeVS0805RJ_T

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902RJ Read this article online and download the SampleWebCloudServiceproject for this article

The SQL Data Services team has promised for months to support schemas and

full-text search in later CTPs

0209vsm_F1Retire_14-25v13 12209 141 PM Page 25

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 28: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Irsquove written before about how much I like lambda expressions and the way type inferences workin C I think lambda expressions have more clarity than the combination of delegate defini-tions and out-of-band method definitions and the related extra work you have to do only to satisfythe language definitions But there are some weaknesses If a methodrsquos parameters contain theSystemDelegate abstract type using lambda expressions introduces special problems The C

compiler canrsquot convert a lambda to some not-yet-defined concrete derived delegate typeWithout some extra thought on your part yoursquoll end up with code that looks like it came from

NET 10 Irsquoll walk you through the exercise of understanding why lambda expressions arenrsquot immediatelyconvertible to abstract delegate types and how you can convince the compiler to convert the specificdelegate type you defined for your use The solution Irsquoll describe relies on Windows Presentation Foundation (WPF) and the SystemWindowsThreadingDispatcher component but this is not strictlya WPF issue The issue described crops up in several locations in the NET Framework including theWindows Forms Office APIs and Reflection APIsYoursquoll be able to follow the approach described in thisarticle 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 thatrsquos some form of delegate Iprefer to use a lambda expression instead of a more verbose representation For example this line of codecreates a SystemWindowsThreadingTimer that calls the method TickHandler when the timer fires

tick = new SystemThreadingTimer((unused) =gt TickHandler())

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server

ASPNET

XML

Lambda expressions arenothing more than convenient syntax for delegates So why canrsquot youuse them where the Framework expects a delegate And more importantly what can youdo about itBY BILL WAGNER

C CO R N E R U S I N G E X P R E S S I O N S

Use Lambda Expressions for Abstract Delegates

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom26

ILLU

ST

RA

TIO

N B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_CCorner_26-29v8 12209 143 PM Page 26

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 29: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 27

If the body of the method were small enough I would replace theTickHandler() method call with the body of the method Thatapproach works fine most of the timebut the same technique doesnrsquotwork when the API uses SystemDelegate as a parameterFor exampleyou use the SystemWindowsControlsDispatcherInvoke() methodto marshal calls across threads in WPF

public object Invoke(delegate methodparams object[] args)

Now consider what happens when you try to use a lambda expres-sion for this call

MyTimeDispatcherInvoke(() =gt DoSomething())

You get the cryptic error

error CS1660 Cannot convert lambda expression to type SystemDelegate because it is not a delegate type

Yoursquoll probably wonder whatrsquos going on the first time you see thiserror Of course itrsquos a delegate type right Well the compiler isnrsquotquite as smart as you areThe SystemDelegate type is an abstract typeand the type inference engine canrsquot infer the number and types of thearguments or the return value for some unknown delegate typederived from SystemDelegateTo fix this problemyou must create aconcrete delegate type and assign your lambda expression to thattype Before you delve too far into the distant past and begin writingC 10 coderemember delegate types let you treat methods as data

I built a WPF timer application to show you how this worksillustrating how a little C 30 can make it easy to work with theseolder APIs (see Figure 1) The timer is quite simple You give it alength of time and press start The background changes from lightgreen to yellow to red as time runs out

Updating the display based on time requires responding toevents from a timer Timers run on background threads so yoursquollrun headlong into the problem I described at the outset

Updating the ApplicationThe UI handling code is straightforward The work happens whenthe timer fires and the code updates the timer display The updatemust change the text and possibly the background for the controlThatrsquos a couple quick lines of code

MyTimeBackground = newBrushMyTimeContent = label

The timer runs on a background thread so you need to marshal thecall across the thread boundary using the DispatcherInvoke()method These two lines of code are what yoursquod want to put in alambda expression not the heavy-duty business logic that justifies amethod definitionBut I said earlier that a lambda doesnrsquot work withDispatcherInvoke It can but you need to use a concrete delegatedefinition Several are defined in NET Framework 35 The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the caseThese two lines also require a pair of parameters a string for the con-tent and a brush for the background color That means you need touse a delegate definition that takes two parameters and returns void

Actionltstring Brushgt updateTimer

After declaring the variableyou can assign the delegate variable to thebody of the code you want to executeYou can use a lambda expres-sion here because ActionltT1T2gt is a concrete delegate definition

updateTimer = (label newBrush) =gt

MyTimeBackground = newBrushMyTimeContent = label

Now yoursquove got a member variable that points to the block of codethat you want to execute when the timer raises its event All thatrsquosleft is to use the delegate definition with DispatcherInvoke()

Whenever yoursquore not sure what thread yoursquore on you can call DispatcherCheckAccess() to determine whether

you can access any UI controls

FIGURE 1 WPF Timer Application Running This sample applicationruns a timer while you practice a presentation The color changes fromgreen to yellow to red as you run out of time Itrsquos a great way to democross-thread calls because the timer runs in a background thread

0209vsm_CCorner_26-29v8 12209 143 PM Page 27

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 30: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom28

if (MyTimeDispatcherCheckAccess())

MyTimeDispatcherInvoke(updateTimer newLabel next)

elseupdateTimer(newLabel next)

This process is straightforward but itrsquos something that yoursquoll dorepeatedly so letrsquos go a few steps further and make this easier to reuse

Therersquos a simple pattern at work hereEvent handlers can be called from a back-ground threadYoursquoll see this behavior whenyou use timers when you call Web servicesasynchronouslyand in other common tasksWhenever yoursquore not sure what thread yoursquoreonyou can call DispatcherCheckAccess() todetermine whether you can access any UI con-trols If you need to marshal a call acrossthread boundaries you must useDispatcherInvoke()The DispatcherInvoke()method avoids several different overloads byusing a params array for any parameters to themethod it uses an abstract delegate type forthe code that you want to execute

You want a single method that checkswhether marshaling is needed If marshal-ing is needed the method marshals thecall otherwise it calls the method pointedto by the delegateYou want that method toappear as if it were a member of the Sys-temWindowsControlsControl class Thisenables you to use the code as if it were partof any control C 30 gives you a way to dothis extension methods You need to write afew different overloads of the methodswhichenables you to use them with different num-bers of parameters

public static class WPFExtensions

public static voidInvokeIfNeeded(this Control widget Action whatToDo)

if (widgetDispatcher

CheckAccess())

widgetDispatcherInvoke(whatToDo)else

whatToDo()

public static void InvokeIfNeededltTgt(this Controlwidget ActionltTgt whatToDo T parm)

Develop your application with the same robust imaging technologies used by MicrosoftHP Sony Canon Kodak GE Siemens the US Air Force and Veterans AffairsHospitals

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

bullImage Formats All industry standardsincluding TIFF EXIF PDF JPEGJPEG2000DICOM PCL DWG and hundreds morebullImage Compression From standardJBIG JBIG2 ABIC JPEG and CCITT G3G4 toLEADrsquos specialized ABC CMP and CMWcompressionbullDisplay Controls Scroll zoom panmagnify glass brightnesscontrastgammawindow levelbullImage Processing 200+ filters trans-forms and color conversion functions withextended grayscale (10 to 16-bit) supportbullOCRICROMR Full page or zonalmulti-threaded recognition with format-ted output including PDF DOC and TXT forWin32 and x64bullBarcode Readwrite all industry standard1D and 2D barcodes (DataMatrix PDF417MicroPDF417 QR Code and more)bullForms Recognition and ProcessingAutomatically identify forms and extract userfilled databullDocument CleanupPreprocessingDeskew despeckle line and border removalregistration marks and morebullPDF and PDFA Readwrite raster andtext searchable PDF filesbullAnnotationsInteractive UI for documentmark-up redaction and image measurement(including support for DICOM annotations)bullGrayscale Imaging Display and processsignedunsigned 10-16 bit 32 bit data

bullMedical Web Viewer Framework Plug-inenabled framework to quickly build highqualityfull-featured web-based medical imagedelivery and viewer applicationsbullMedical Image Viewer High level displaycontrol with built-in tools for image mark-upwindow level measurement zoompan cineand LUT manipulationbullDICOM Full support for all IOD classes andmodalities defined in the 2008 DICOM standard(including Encapsulated PDFCDA and RawData)bullDICOM Communications Full support forDICOM messaging and secure communicationenabling quick implementation of any DICOMSCU and SCP servicesbullWPF (XAML) Viewer Image ListAnnotations Transitions and WIC CodecsbullAJAX Web Form Image controls fordeveloping rich web applicationsbullJPIP Client and Server components forinteractive streaming of large images andassociated image data using the minimumpossible bandwidthbullScanning TWAIN and WIA(32 and 64-bit)autodetect optimum driver settings for highspeed scanningbullDVD Play create convert and burn DVDimagesbullMultimedia Capture play stream andconvert MPEG AVI WMV MP4 MP3 OGGISO DVD and more

Free 60 Day Evaluation wwwleadtoolscomvsm 800 637-1840LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

LEADTOOLS v16 ndash NET WPF WCFWF C API C++ Class Lib COM amp more

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

0209vsm_CCorner_26-29v8 12209 143 PM Page 28

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 31: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

C C O R N E R raquo U S I N G E X P R E S S I O N S

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom 29

if (widgetDispatcherCheckAccess())

widgetDispatcherInvoke(whatToDo parm)else

whatToDo(parm)

public static void InvokeIfNeededltT1 T2gt(this Controlwidget ActionltT1 T2gt whatToDo T1 parm1 T2 parm2)

if (widgetDispatcher

CheckAccess())widgetDispatcherInvoke(whatToDo parm1 parm2)

elsewhatToDo(parm1 parm2)

Of course you can extend this class byadding more overloads with more parame-ters Itrsquos a simple extension

There was a method to the WPF design-ersrsquomadness They wanted to make it as easyas possible to use the Dispatcher object byminimizing the surface area of the API Byusing abstract delegates and params on theparameter list this object is usable in thewidest possible number of scenarios Anymethod with any number of parameters canbe used However that comes with a down-sideThis more abstract API removes all typesafety and this hurts the compilerrsquos ability touse type inference to make you more produc-tive The work around is to add your ownlayer of type-safe extension methods thatprovide a layer between your type safe callsand the more abstract NET library API VSM

Bill Wagner author of ldquoEffective Crdquo (2004)and ldquoMore Effective Crdquo (2008) both fromAddison-Wesley Professional has been a com-mercial software developer for the past 20 yearsHe is a Microsoft regional director and a VisualC MVPHis interests include the C languageNET Framework and software design E-mailWagner at wwagnersrtsolutionscom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly tothese related resources

READ amp DOWNLOAD

VS0902CC Read this article and download the sample code online

Develop your application with the samerobust imaging technologies used byMicrosoft HP Sony Canon Kodak GESiemens the US Air Force and VeteransAffairs Hospitals

Free 60 Day Evaluation wwwleadtoolscomvsm

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

The LEADTOOLS Competitive UpgradeCall Our Sales Dept (800) 637-4699

for details Valid through March 31 2009

Mark-up DICOM Medical

Form Recognition amp Processing

Multimedia

Document Barcode

Chosen by thousands of companies for use in their high volume applications and internal systems

bull One Company For Any Imaging Needbull Flexible Licensing Royalty Free Optionsbull Time Tested Easy to Usebull Free Technical Support

LEADTOOLS SDKs feature LEADrsquos iCompresstrade Technologies

0209vsm_CCorner_26-29v8 12209 143 PM Page 29

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 32: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Brought to you by

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27 2009

bull Attend the Microsoft MSDN Developer Conference FREE (pre-con event Monday Feb 23 Space is limited fi rst come fi rst served)

bull Participate in the NEW VSLive After Darkmdashan informal open ended chat with VSLive speakers attendees and industry experts

bull Listen to amazing speakers in over 80 sessions spanning existing technologies Microsoftrsquos newest releases and yet-to-be-shipped tools

bull Visit the Exhibitor Expo and VIP Lounge amp Game Center (sponsored by ComponentOne)

bull Book signings with some of your favorite technical authors

Join us at VSLive San Francisco and you can expect these great activities

To view the complete agenda and register for VSLive go to vslivecomsf2009

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

Take advantage of this recession busting breakmdashregister for VSLive and bring a colleague absolutely FREE OF CHARGE Thatrsquos up to an $1800 savings to you and your company

Buy One VSLive Conference Registration Get One FREE

Calling All Developers mdash VSLive Is Expecting You

VSL_VSM_Feb09indd 1VSL_VSM_Feb09indd 1 12009 124330 PM12009 124330 PM

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 33: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Meet these Experts in Person at VSLive San FranciscoRockford Lhotka on Silverlight and Building Distributed Apps in NET 35 SP1Lhotka 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

Aaron Skonnard on ldquoDublinrdquo Windows Azure and Whatrsquos New in WCFWF 40

Skonnard is co-founder of the Microsoft NET training provider Pluralsight and author of numerous books articles whitepapers and courses

Bill Vaughn on ADONET 35 SP1 for Visual Studio and SQL Server and Visual Studio ReportingmdashLeveraging the New SQL Server 2008 RDL Technology

Vaughn is a 35-year veteran of the computer industry author of the critically acclaimed book ldquoHitchhikerrsquos Guide to SQL Server 2000 Reporting Servicesrdquo and top expert on Microsoft Visual Studio SQL Server Reporting Services and data access interfaces

Dave Bost on Prism and a deep dive into ASP NET 35 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

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

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

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 ldquoBest Kept Secrets in NETrdquo

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

2 FOR 1SAVINGS

UP TO$1800

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 fi rst conference pass

VSL_VSM_Feb09indd 2VSL_VSM_Feb09indd 2 12009 124335 PM12009 124335 PM

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 34: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom32

TECHNOLOGY TOOLBOX

VBNET

C

SQL Server 2005

ASPNET

Iterators are a crucial part ofmodern programming notleast because they providethe basis for collection traversal using For Each loopsLanguage Integrated Query(LINQ) adds to the importanceof iterators as iterators arethe source of IEnumerable(OfT) that forms the backboneof LINQ Learn how to takeadvantage of them in yourcode with several differenttechniques for creating yourown iterators in VBBY BILL MCCARTHY

In Visual Studio 10Visual Basic and C will officially attempt to converge rather than divergeThe two languages are touted by Microsoft to have the same major language features as eachother Microsoft also promises ldquolanguage parityrdquoand ldquoan end to the sibling rivalryrdquoFor C thismeans the inclusion of long-standard VB features such as late binding and optional parametersFor VB it means the inclusion of multi-expression lambdas and auto properties This parity is

not absolute For example C wonrsquot have XML literals making VB still the best language for workingwith 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 anenumerable object in a single method An enumerable object is one that you can perform For Eachloops or LINQ queries on Arrays Lists and Collections are all common examples of enumerableobjects In fact enumerable objects are so common in the NET Framework that you rarely need todefine your own Still itrsquos important you understand the basics of what enumerable objects are and howto create them should the need ever arise

Letrsquos kick things off with some common examples for iterators yoursquoll see in C The first is from theC documentation

public int[] items

public IEnumerable BuildCollection()

for (int i = 0 i lt itemsLength i++)

Use Iterators in VB Now

PH

OT

O B

Y I

ST

OC

KP

HO

TO

CO

M

0209vsm_OnVB_32-38v9 12209 136 PM Page 32

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 35: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 33

yield return items[i]

I hope yoursquore laughing at that sample If you arenrsquot some explana-tion might help you see the humor The code shows a method thatreturns an IEnumerable This is what an iterator is in C The ldquoyieldreturnrdquostatement indicates what is returned when the code is enu-merated with a For Each loop or similar So this code iterates overan array and returns each item in the array In other words it issuperfluous and just adds overhead as an array is already enu-merable That method could have just returned the array cast toan IEnumerable

You might think thatrsquos just a one-off bad-code example SadlyI have seen many cases where iterator blocks are superfluousSuperfluous code is an evil because it adds to the testing and main-tenance burdens But not all cases are superfluous Bill Wagner inhis December 2008 C column (ldquoWhat VB Devs Should KnowAbout Crdquo) showed a good example of creating an iterator that willgive you the letters ldquoardquoto ldquozrdquoas you enumerate it

public static IEnumerableltchargt Letters()char currentCharacter = adoyield return currentCharacter

while (currentCharacter++ lt z)

This code shows an important aspect of iterators Theyrsquore statemachines The variable currentCharacter is modified each timeyou enumerate the IEnumerable returned from Letters To achievethe same result in VB could require some substantial work on yourpart but there are as they say many ways to skin a cat (note nofelines were harmed in the production of this code) For exampleyou could create an array of Char populate it and return that

Dim letters(0 To 25) As CharFor i As Int32 = 0 To 25letters(i) = ChrW(ampH61 + i)

Next

This will work but itrsquos a bit messy An alternative approach is torefactor this methodThe code inside the For i As Int32 = 0 to 25 loopis an expression in a range so you can use the EnumerableRangemethod as part of a LINQ expression

Dim letters = From i In EnumerableRange(0 26) _Select ChrW(ampH61 + i)

This is a little better but there are other ways to approach thisproblem as well A String is in fact enumerable and implementsIEnumerable(Of Char) so you can simplify everything to a singlestring declaration

Dim letters = abcdefghijklmnopqrstuvwxyz

This alternative certainly seems far more maintainable and a lotmore obvious too

Of course this example is a simple one If it were more complexsuch as fetching values from somewhere or calculating the values thedifferences between the solutions become much more meaningfulBoth the first and last solution are based on having the complete set ofcharacters in memory to begin with whereas the solution that usesthe EnumerableRange method loads the characters only when youiterate over the lettersThis is often referred to as ldquodelayed evaluationrdquo

Delayed evaluation or ldquoon-demand evaluationrdquoas I prefer tocall it is an important aspect of iterators and especially of LINQItrsquos also something you need to be wary of when translating C codeto VB or when you look for alternatives to iterators Typically LINQexpressions and utility methods such as Range provide solutionsthat have the desired on-demand evaluation behavior

However there are times when you will find it necessary towrite an iterator One such case occurred for me recently I wanted

FIGURE 1 Create the Interfaces of an Iterator VB doesnrsquot comewith iterators out-of-the-box as the next version of C will but itrsquospossible to create your own and what you can create is more versa-tile than the plain-vanilla iterators yoursquoll be able to create with the nextversion of C These are the interfaces and the members you mustimplement to create your own iterator

I have seen many cases where iterator blocks are superfluous Superfluous code is an evil because it adds to the

testing and maintenance burdens

0209vsm_OnVB_32-38v9 12209 136 PM Page 33

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 36: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

to read from a stream line-by-line search for a substring andreturn the first couple of matches Unfortunately StreamReaderdoesnrsquot have an iterator that returns each line Without somethingthat is enumerable you canrsquot form the basis of a LINQ query soyoursquore forced to write your query imperatively Thatrsquos not as bad asit might first sound VB developers were doing this successfully foryears before LINQ came along

strLine = myStreamReaderReadLineDo While strLine IsNot Nothing

If strLineContains(value) Thencount += 1resultListAdd(strLine)If count gt= 3 Then Exit Do

End IfstrLine = myStreamReaderReadLine

Loop

Building the query into the imperative procedural block doeswork although itrsquos kind of on the ugly side I look at that code

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom34

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

Module StreamExtensions

ltExtension()gt _Function Lines(ByVal rdr As TextReader) _As IEnumerable(Of String)Return New StreamReaderLineEnumerator(rdr)

End Function

End Module

Public Class StreamReaderLineEnumeratorImplements IEnumerable(Of String)Implements IEnumerator(Of String)

Private _rdr As TextReaderPrivate _current As String

Sub New(ByVal rdr As TextReader)_rdr = rdr

End Sub

ltsummarygt Gets an enumerator to read lines from a stream ltsummarygt ltreturnsgtIEnumerator(Of String)ltreturnsgt ltremarksgtCan only be called once due to the underlying stream Not thread safeltremarksgt ltexception cref=InvalidOperationExceptiongt thrown if GetEnumerator is called more than onceltexceptiongtPublic Function GetEnumerator() _As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement( _iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _GetEnumerator can only be called amp _

once on a stream)End If

End Function

Private Function IEnumerator_GetEnumerator() _As IEnumerator _Implements IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

Public ReadOnly Property Current() As String _Implements IEnumerator(Of String)CurrentGetReturn _current

End GetEnd Property

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNext_current = _rdrReadLine()Return _current IsNot Nothing

End Function

Private Sub Reset() Implements IEnumeratorResetThrow New NotImplementedException()

End Sub

Public Sub Dispose() Implements _IDisposableDisposenot 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 MoveNextmethod This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler The extension method willshow up on an instance of the StreamReader class as a Lines function

VB EXTEND THE STREAMREADER CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 34

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 37: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 35

and it screams to me that it needs to be beautified Irsquom not thetype of person who tends to talk about beautifying codemdashtheMay 2007 On VB column headlineldquoBeautify Your Coderdquowas cre-ated by an editormdashbut an extension method is the kind of thingthat can help you add some beauty to this code

If you have an extension method named Lines that returnsan IEnumerable with each item a line then you can create a querylike this

Dim result = From line In myStreamReaderLines _Where lineContains(value) _Take 3

I think that approach is a clear winner for the most beautiful solu-tion The difficulty is in creating the Lines extension method If youdonrsquot mind having a C assembly as a reference itrsquos a simple task tocreate an Extension method thatrsquos an iterator

static class StreamExtensionsstatic public IEnumerableltStringgt Lines(this TextReader rdr)

String linewhile ((line = rdrReadLine()) = null)yield return line

This can take substantially more work in VBYou have to implementIEnumerable(Of T) and IEnumerator(Of T)which also includes thenon-generic IEnumerable IEnumeratorand IDisposable interfacesThatrsquos a class (or classes) with at least seven members eight if you

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 TPrivate _func As MoveNextFunc

Public Sub New(ByVal func As MoveNextFunc)_func = func

End Sub

Public Function MoveNext() As Boolean _Implements IEnumeratorMoveNextReturn _func(_Current)

End Function

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable(Of T)GetEnumeratorStatic iBeenCalled As Int32If (iBeenCalled = 0) AndAlso _(ThreadingInterlockedIncrement( _iBeenCalled) = 1) Then

Return MeElseReturn New GenericIterator(Of T)(_func)

End IfEnd Function

Public ReadOnly Property Current() As T _Implements IEnumerator(Of T)Current

GetReturn _Current

End GetEnd Property

Public Overridable Sub Reset() _Implements IEnumeratorResetThrow New NotImplementedException( _Iterator cannot be reset)

End Sub

Private Function _IEnumerator_GetEnumerator() As IEnumerator _Implements IEnumerableGetEnumeratorReturn MeGetEnumerator

End Function

Private ReadOnly Property IEnumerator_Current() _As Object Implements IEnumeratorCurrentGetReturn MeCurrent

End GetEnd Property

Public Sub Dispose() _Implements IDisposableDispose 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 thisgeneric template in VB8 and VB9 but without support for multi-statement lambdas yoursquoll find that yoursquoll need to use AddressOf and capturevariables used by making them fields of a wrapper class As a consequence yoursquore better off using the direct implementation (Listing 1opposite page) rather than the generic template for versions of VB prior to VB10

VB CREATE A GENERICITERATOR CLASS

0209vsm_OnVB_32-38v9 12209 136 PM Page 35

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 38: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom36

include the constructor (see Figure 1 p 33) The good news is thatmost of these methods are typically implemented with the sameboilerplate code This means that you can streamline creating itera-tors in VB by using techniques such as snippets templates orgeneric classes

You must implement three methods for the IEnumerator

interface MoveNext Reset and Current a ReadOnly propertyReset is seldom used It canrsquot be used inside a For Each loop sofor most of your implementations you can Throw a NotImple-mentedException as the body of the Reset method The impor-tant method is MoveNext In the MoveNext method you deter-mine whether there are more items to return If there are you

store the next item to return in the Cur-rent property This means the Currentproperty needs to return only a field

Next add the generic interface IEnu-merator(Of T) Then add Current As T astrongly typed ReadOnly Property as wellas an IDisposableDispose implementa-tion At this point you have two ReadOn-ly properties named Current that wonrsquotcompile or you have one named Currentand the other named Current1 A goodway to deal with this is to make the leaststrongly typed method Private Thisallows you to give the method a name forinternal use You can still access the pri-vate method externally through a cast tothe interface

Private m_Current As T

Public ReadOnly Property _Current() As T _Implements IEnumerator( _Of T)Current

GetReturn m_Current

End Get

End Property

Private ReadOnly Property _IEnumerator_Current() _As Object _Implements IEnumeratorCurrentGetReturn Current

End GetEnd Property

You must also implement IEnumera-ble(Of T) This includes a single function(GetEnumerator) in which you returnyour IEnumerator(Of T) implementationAs part of the IEnumerable(Of T) inter-face you must also implement the non-generic IEnumerable interface IEnumer-able also has a GetEnumerator function

The NExT Step In Document

and Photo Imaging

wwwatalasoftcom

New features to our already powerful imaging toolkit include PDFA

support AJAX Vector Annotations including FreeHand WPF annota-

tions and more Use templates in our AJAX Wizard to create zero-

footprint web applications in C and VBNETmdashTake document and

photographic imaging to the NExT step

Visit Atalasoftcom for web demos video tutorials and a free trial

Atalasoft Your NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 70mdashMore Powerful

with Zero-Footprint Imaging and

3 Months of Free Gold Support

New

DotImage 70

Release

0209vsm_OnVB_32-38v9 12209 136 PM Page 36

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 39: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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 LO N V B raquo I T E R AT O R S I N V B

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 37

but its return type is the non-generic IEnu-merator As you did with the Current prop-erty and IEnumerator make the IEnumer-able GetEnumerator method Private andhave it call the more strongly typed genericmethod

Public Function GetEnumerator() _As IEnumerator(Of T) _Implements IEnumerable( _Of T)GetEnumeratorTODO add implementation here

End Function

Private Function _IEnumerable_GetEnumerator() _As IEnumerator Implements _IEnumerableGetEnumeratorReturn GetEnumerator()

End Function

The code you put inside the GetEnumera-tor method deserves careful considerationYou need to think through how you expectthese implementations to be used as wellas how they will behave in cases such asmulti-threaded environments or whenchanges occur Enumerators are normallyconsidered to be a snapshot For exampleList(Of T)rsquos enumerator will throw a run-time exception if the list is changed duringa For Each iteration Other iterators mightjust ignore changes In the case of a streamyour decision is a bit tougher

You change a streamrsquos position as youread from it For example if there are twoiterators reading from the one stream theresults could be unpredictable changingdepending on threading behaviors Thereare two ways around this problem Use anull stream and have the iterators returnno data or throw an exception in GetEnu-merator if it has been called previouslyThrowing an exception makes it easier todebug what went wrong Whicheverchoice you make take the time to docu-ment it by completing the XML commentson the method

The VB version is obviously lengthier than the C version but the VB version has some

significant benefits

0209vsm_OnVB_32-38v9 12209 136 PM Page 37

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 40: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

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

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom38

ltsummarygtltsummarygt

ltreturnsgt ltreturnsgtltremarksgt

ltremarksgtltexception cref=InvalidOperationExceptiongt

ltexceptiongtPublic Function GetEnumerator() As IEnumerator(Of String) _Implements IEnumerable(Of String)GetEnumeratorStatic iFirstTime As Int32If iFirstTime = 0 AndAlso _ThreadingInterlockedIncrement(iFirstTime) = 1 ThenReturn Me

ElseThrow New InvalidOperationException( _

)

End IfEnd Function

There are a couple of points worth discussing in this code The coderelies on a static variable inside the code to check whether themethod has been called previously and uses ThreadingInter-lockedIncrement to change the value This ensures that it can becalled only once even in a thread-race condition If it has beencalled more than once an InvalidOperationException is thrownNote that the method returns a Me reference when called for thefirst time This is because the class implements both the IEnumer-able(Of T) interface and the IEnumerator(Of T) interfaceYou canseparate them into different classes but often itrsquos useful to havethem in a single class because you generally need to store someshared state in them (see Listing 1 p 34 for a complete example ofa StreamReaderLineEnumerator)

The VB version is obviously lengthier than the C versionbut the VB version has some significant benefits First yourimplementation is likely to be more robust because yoursquove beenforced to look at the implementation details Second the C ver-sion doesnrsquot prevent GetEnumerator being called more thanonce on the same stream This could result in some obscurethreading problems It could also produce seemingly null resultsets for files if the iterator is called twice Or it could potentiallyresult in some object-disposed exceptions occurring that arenrsquotexplicit in describing the real problem The C version does pro-vide a quick-and-dirty way to write the iterators The quick partis inviting but itrsquos often the dirty part that we spend a lot moretime cleaning up after

Itrsquos important to note that iterators in C arenrsquot always dirtySometimes they do provide an elegant and clean way to express anIEnumerable And itrsquos likely VB will get a similar syntax in thenot-too-distant future In VB10 you will be able to use multi-statement lambdas that capture surrounding variables If yoursquorewilling to accept the same limitations that iterators have in Cthen you can use a lambda as the basis for the MoveNext method

and combine this with a generic template to give you the samefunctionality from VB

To do this you need to define a delegate in your generic tem-plate that has the current item as a ByRef parameter

Public Delegate Function MoveNextFunc( _ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor stores a ref-erence to it and calls that in the MoveNext method Once youdefine the GenericIterator class (see Listing 2 p 35) you can usethis much as you use inline iterators in C For example you cancreate a line-by-line iterator with a StreamReader

Dim lines = New GenericIterator(Of String) _(Function(ByRef nextItem As String) As BooleannextItem = rdrReadLineReturn nextItem IsNot Nothing

End Function)

The lack of a formal syntax for iterators in VB doesnrsquot mean you canrsquotcreate iterators in VB In fact the download for this article includes asnippet templatesand examples of how you can write iterators easilyin the current version of VBThe download also includes an examplethat illustrates how to use a generic template and lambdas in VB10Using the downloadable snippet or templates in the current version ofVB you can quickly create iterators that are more flexible and morerobust than what the C iterator syntax allows for

As LINQ and PLINQ become more a part of your program-ming your reliance on iterators will increase so nowrsquos a good timeto learn how to write them properly Being exposed to the imple-mentation details will give you a better understanding of iteratorsand their pitfalls which means yoursquoll be less likely to yield to thetemptation of using them poorly when the day comes that VB tooadds some syntactic sugar for creating iterators

So grab these downloads and start writing your own itera-tors today VSM

Bill McCarthy is an independent consultant based in Australia andis one of the foremost NET language experts specializing in VisualBasic Hersquos been a Microsoft MVP for VB for the last 10 years and satin on internal development reviews with the Visual Basic team forthe last five years where he helped to steer the languagersquos future direction These days he writes his thoughts about language directionon his blog at httpbillmccarthycom

GO ONLINE

Use this Locator+ code at VisualStudioMagazinecom to go directly to theserelated resources

READ amp DOWNLOAD

VS0902OV Read this article and download the sample code online

GetEnumerator can only be called once on a stream

thrown if GetEnumerator is called more than once Not thread safe underlying stream from a stream

IEnumerator(Of String)

Gets an enumerator to read lines

Can only be called once due to the

0209vsm_OnVB_32-38v9 12209 136 PM Page 38

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 41: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VisualStudioMagazinecom middot February 2009 middot VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone 508-532-1433amintz1105mediacom

Chris KourtoglouRegional Sales ManagerPhone 415-814-0955ckourtoglou1105mediacom

National Accounts DirectorWilliam SmithPhone 603-886-3466wsmith1105mediacom

Microsoft Account ManagerDanna VedderPhone 253-514-8015dvedder1105mediacom

West

East

Director Print ProductionJenny Hernandez-AsandasPhone 818-734-1520 ext 101Fax 818-734-1528jhernandez1105mediacom

Production CoordinatorCatharine WoodPhone 818-734-1520 ext 233vsmadproduction1105mediacomcwood1105mediacom

Advertising Sales Ad IndexAtalasoft Inc 36wwwatalasoftcom

dtSearch 12wwwdtsearchcom

ESRI 7wwwesricom

Intel Corporation C4wwwintelcom

LEAD Technologies Inc 28 29 wwwleadtoolscom

Microsoft Corporation 20 21wwwmicrosoftcom

Pegasus Imaging Corporation 37 wwwpegasusimagingcom

Software FX Inc C2 1 wwwsoftwarefxcom

TallApplications BV 2wwwdeepseaobfuscatorcom

TallComponents BV C3wwwtallcomponentscom

Visual Studio Magazine 9wwwvisualstudiomagazinecom

VSLive San Francisco 30 31wwwvslivecom2009sf

Wayside Technology Group Inc 5wwwwaysidetechnologycom

Edit Ad IndexCombit GmbH 11wwwcombitneten

DataDirect Technologies 11wwwdatadirectcom

MadCap Software 13wwwmadcapsoftwarecom

Resco 12wwwresconet

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc 9121 Oakdale Avenue Ste 101Chatsworth CA 91311 Periodicals postage paid atChatsworth CA 91311-9998 and at additional mailingoffices Complimentary subscriptions are sent to qualifyingsubscribers Annual subscription rates for non-qualified sub-scribers are US $3497 Canada $5297 (US funds)International $7897 (US funds) Subscription inquiriesback issue requests and address changes Mail to VisualStudio Magazine PO Box 1164 Skokie IL 60076-8164email VSM1105servicecom or call toll free 888-768-8759fax number 847-763-9564 International calls 847-763-9135 POSTMASTER Send address changes to Visual StudioMagazine PO Box 1164 Skokie IL 60076-8164 CanadaPublications Mail Agreement No 40612608 ReturnUndeliverable Canadian Addresses to Circulation Dept orBleuchip International PO Box 25542 London ON N6C 6B2

Copyright Statementcopy Copyright 2009 by 1105 Media Inc All rights reservedPrinted in the USA Reproductions in whole or part prohib-ited except by written permission Mail requests toPermissions Editor co Visual Studio Magazine 230California St San Francisco CA 94111

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media Inc and is distributed with-out any warranty expressed or implied Implementation oruse of any information contained herein is the readers soleresponsibility While the information has been reviewed foraccuracy there is no guarantee that the same or similar

results may be achieved in all environments Technical inac-curacies may result from printing errors andor new develop-ments in the industry

Corporate AddressCorporate Headquarters 1105 Media9121 Oakdale Ave Ste 101Chatsworth CA 91311www1105mediacom

Media KitsDirect your Media Kit requests toMatt Morollo VP PublishingPhone 508-532-1418 Fax 508-875-6622 E-mail mmorollo1105mediacom

ReprintsReprints For single article reprints (in minimum quantities of250-500) e-prints plaques and posters contactPARS InternationalPhone 212-221-9595E-mail 1105reprintsparsintlcomWeb wwwmagreprintscomQuickQuoteasp

List RentalThis publicationrsquos subscriber list as well as other lists from1105 Media Inc is available for rental For more informa-tion please contact our list manager Merit Direct Phone 914-368-1000E-mail 1105mediameritdirectcomWeb wwwmeritdirectcom

Go toVisualStudioMagazinecomto access the stories in thisissue plus read exclusiveonline-only content

0209vsm_AdIndex_39v3 12209 144 PM Page 39

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 42: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

VISUAL STUDIO MAGAZINE middot February 2009 middot VisualStudioMagazinecom40

WHERE DID ALL THEDEVELOPERS GO

VBNET have been declining to the point where they are nowbelow those for C

This of course means nothing For one thing VisualBasic programmers use more than one search term (VBVBNETVisual Basic) while C programmers use only C sototal VB searches while trending downward are probably stillwell above C Besides the whole VB versus C discussion istiresomemdashthe framework is where the real excitement is IfC use is growing at the expense of VBNET who cares

Except that it isnrsquot growing The real surprise in the trendline was that C searches have been flat for years This promptsthe question If programmers are leaving VB and arenrsquot goingto C where are they going Could it be that theyrsquore abandon-ing Microsoft technologies

I checked the trend lines for other programming lan-guages and platforms including PHP Perl Java JavaScriptand Flash programming I discovered that C by holding flatis doing well because every other ldquotraditionalrdquo language istrending downward

Why would this be Perhaps developers are usingLivecom instead of Google Irsquod accept that if it were just theMicrosoft languages but LAMP programmers leaving Googlefor Livecom I donrsquot think so Something real is happening

Does use of language names as search terms correspondto the popularity of a language After allexperienced developersdonrsquot often search for language namesmdashwersquore much better atrefining our searches People use language names as searchterms when theyrsquore curious about them or when theyrsquore juststarting out They use them to find introductory articles andtutorials So wersquore most likely looking at a specific populationnew developers and those who are switching languages Couldthe declining trend lines be indicating an overall drop in interestin computer programming Could it indicate a movementaway from traditional programming to newer platforms

Itrsquos probably both Statistics from the US Department ofEducation and National Science Board concur Enrollment

and degrees granted in computer science programs have beendropping recently This year many colleges (including top-tierprograms such as MIT Rutgers and Berkeley) report lowerenrollment Carnegie Mellon one of the top computer scienceschools in the country had only 2000 applicants for its com-puter science department down from 3200 in 2001

Google Trends is little more than a curiosity a signpost toreality The surge of people who entered programming in thersquo80s is drifting away Fewer people are entering the field Thesoftware development world has fragmented with program-mers being drawn from mainstream-development platformsto new technologies such as iPhone and Facebook applicationdevelopment (both of which are trending upward)

Therersquos another reality to be found on Google Trends Italso lists the regionscitiesand languages where a search term ismost popular Keeping in mind that language terms are mostpopular with beginners and those learning a new language itrsquosinteresting to note that the top three regions for C are IndiaSouth Africa and Israel (the United States is No 10) that theseven top cities are in India and Chinaand that the No1searchlanguage is Chinese Indeed similar region and language trendsapply across every language and dev platform I checked

Where have all the coders gone Now we know But per-haps the better question is Where are the new coders going tocome from Thatrsquos something you can help answer by teachingyour kids to code and by volunteering to help introduce orteach programming in your local schools and community colleges And if you arenrsquot part of creating the answer donrsquotcomplain if you donrsquot like the answer you get VSM

Dan Appleman is a Microsoft Visual Basic MVP webmaster ofSearchDotNetcom CEO of Desaware Inc co-founder of Apressand sometime author speaker and blogger who has throughouthis career insisted that you canrsquot talk technology without also discussing its human and financial impact You can reach himat dandesawarecom

The Human Factor

BY DANIEL APPLEMAN

Google Trends (trendsgooglecom) is a curious tool It displays the relativepopularity of search terms over timeRecentlya group of developers on asoftware-developers forum noted that over the past five years searches for

0209vsm_GuestOp_40v8 12209 138 PM Page 40

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 43: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

Project3 12109 1134 AM Page 1

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index
Page 44: RETIRE YOUR DATA CENTER - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_902DG.pdfRETIRE YOUR DATA CENTER ... the .NET Insight e-mail newsletter brings you up-to-date news, ... software

EVOLVE YOUR CODEParallelism breakthrough

Analyze compile debug check and tune your code for multicore with Intelreg Parallel Studio Designed for todayrsquos serial apps andtomorrowrsquos parallel innovators

Learn more and sign up for Beta wwwintelcomgoparallel

copy 2009 Intel Corporation All rights reserved Intel and the Intel logo are trademarks of Intel Corporation in the US and other countries Other names and brands may be claimed as the property of others

Project3 11609 856 AM Page 1

  • Back
  • Print
  • Visual Studio Magazine February 2009
    • Contents
      • Features
        • Retire Your Data Center
          • Columns
            • C CORNER Use Lambda Expressions for Abstract Delegates
            • ON VB Use Iterators in VB Now
              • Departments
                • Editorrsquos Note
                • Letters to the Editor
                • First Looks
                  • Product Listings
                  • Review
                    • The Human Factor
                        • Advertiser Index