visual studio magazine - 02- 2009.pdf

Upload: kovacs-gabi

Post on 08-Oct-2015

54 views

Category:

Documents


0 download

TRANSCRIPT

  • PLUS

    Use Lambda Expressionsfor Abstract Delegates

    Use Iterators in VB

    FEB

    RU

    AR

    Y 2

    00

    9

    Vol

    . 19

    , N

    o. 2

    RETIRE YOURDATA CENTERUse Azure Services to Maximize Availability,Reliability, and Scalability.

    VisualStudioMagazine.com

    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

    0209vsm.C1.v2 1/22/09 1:31 PM Page 1

  • BeTheDataGuru

    Visual Studio WPF/Silverlight SharePoint SQL Server PowerShellJava COM

    Project5 12/11/08 4:42 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 options,aesthetics 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 ASP.netapplications. 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 sidebar.IT professionals can now create gadgetsthat consume data from WMI, Exchange,SQL Server and even the Windows Registry.PowerGadgets 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 decades,Software 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 thats clearly on top.

    AchieveAHigherStateOfDataVisualization

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

    Project5 12/11/08 4:43 PM Page 2

  • Project4 6/2/08 12:13 PM Page 1

  • www.visualstudiomagazine.com February 2009 VISUAL STUDIO MAGAZINE 3

    C# CORNER

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

    ON VB

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

    DEPARTMENTS6 Editors 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, ASP.NET, 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 scalability,while you pay only for resources consumed. BY ROGER JENNINGS

    COLUMNS

    14

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

    Roger Jennings, Retire Your Data Center, p. 14

    ILLU

    ST

    RA

    TIO

    N B

    Y R

    AN

    DY

    LY

    HU

    S

    ContentsFebruary 2009 VOLUME 19 NO. 2

    32

    0209vsm_TOC_3-4.v10 1/22/09 1:33 PM Page 3

  • VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com4

    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 needs?You could spend hours or even daystrying to find the answers yourself, oryou could let the experts do it for you.Redmond 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 solutionstheyve come up with. Whether its Web design, .NET development, or SQLServer programming, weve got an event that matches your needs. VisitRedmondEvents.com to learn more about upcoming conferences and shows.

    ONLINE ARTICLES

    Practical ASP.NET: Decoding RoutesIn his ongoing series on ASP.NET, Peter Vogel talks about the routingfeature included in Service Pack 1 for .NET 3.5 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 ASP.NET: Supporting RoutingIn this edition of Peter Vogels Practical ASP.NET 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 users.LOCATOR+ CODE: VS0902PV2

    ONLINE BLOGS

    VSMs Big IssueVisual Studio Magazines 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 VisualStudioMagazine.com

    ContentThe blog will feature opinions and interviews with industryinsiders, and pose questions designed to stimulate discussion.Check out their blog at VisualStudioMagazine.com.LOCATOR+ 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 cantreproduce in the Classic Visual Basic IDE? Or even worse,that only occurs on the clients 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 Right!Conventional wisdom has it that version 1 of any Microsoftproduct or idea is really an alpha, that version 2 is the beta,and 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 E.Peterson takes a trip down memory lane to one of the mostdurable version 3 products ever to come out of Redmond.LOCATOR+ CODE: VS0902KP2

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

    VirtualizationReview.com1105 Media recently launcheda new Web site devoted exclusively to covering allaspects of IT virtualization.Virtualization Review.comhelps you harness the powerof virtualization by delivering

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

    0209vsm_TOC_3-4.v10 1/22/09 1:33 PM Page 4

  • programmersparadise.com800-445-7899

    Your best source for software development tools!

    Prices subject to change. Not responsible for typographical errors.

    programmers.com/theimagingsource

    Download a demo today.

    New Release!

    Professional EditionParadise #

    T79 02101A01$919.99

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

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

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

    Ready-to-use toolbars and dialog boxes

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

    programmers.com/telerik

    Telerik RadControlsby Telerik Add grid, combo, editing, navigation and charting functionality to your AJAX and ASP.NET projects.RadControls for ASP.NET enhances your Web applications by adding AJAX functionality to yourASP.NET projects. The suite takes full advantage of the features included in Visual Studio 2005.RadControls for ASP.NET helps developers deliver feature-rich, standards-compliant (WAI-A, WCAG 1.0, XHTML 1.1) and cross-browser compatible Web applications, while significantly cutting their development time. RadControls for ASP.NET includes: RadEditor, RadTabstrip, RadInput,RadCalendar, RadUpload, RadWindow, RadAjax,RadGrid, RadCombobox, RadMenu, RadSpell,RadChart, RadTreeview and more.

    Single DeveloperParadise #

    TB3 01101A01$648.99

    dtSearch Engine for Win & .NETAdd dtSearchs blazing speeds (CRN Test Center) searching and file format support dozens of full-text and fielded

    data search options file parsers/converters for hit-highlighted

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

    highlights hits with links, images, etc. intact API supports .NET, C++, Java, SQL and more;

    new .NET Spider API

    Bottom line: dtSearch manages a terabyte of text in a single index and returns results in less than a second. InfoWorld

    programmers.com/dtsearch

    Single ServerParadise #

    D29 02101A07 $949.99

    New64-bit

    Version!

    programmers.com/sparxsystems

    New Release!

    Enterprise Architect 7.1Visualize, Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensive,integrated UML 2.1 modeling suite providing key benefits at each stage ofsystem development. Enterprise Architect7.1 supports UML, SysML, BPMN andother open standards to analyze, design,test and construct reliable, well under-stood systems. Additional plug-ins arealso available for Zachman Framework,MODAF, DoDAF and TOGAF, and to integrate with Eclipse and Visual Studio2005/2008.

    Corporate Edition1-4 Users

    Paradise # SP6 0001

    $196.99

    programmers.com/multiedit

    Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers, a powerful IDE,with its speed, depth, and support forover 50 languages. Enhanced searchfunctions include Perl 5 RegularExpressions and definable filters.Supports large DOS/Windows, UNIX,binary and Mac files. File SyncIntegration for: Delphi 6, 7, 2005,C++Builder 6, BDS 2006 and RadStudio2007, VB 6, VC 6, VS 2003 & VS2005. Includes file compare, code beautifying, command maps, and much more.

    1-49 UserParadise #

    A30 01201A02$161.99

    New Release!

    programmers.com/lead

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

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

    Paradise # L05 03201A01$2,007.99

    New Version

    16!

    programmers.com/nsoftware

    /n software Red CarpetSubscriptions by /n software/n software Red Carpet Subscriptions giveyou everything in one package: communica-tions components for every major Internet protocol, SSL and SSH security, S/MIMEencryption, Digital Certificates, Credit CardProcessing, ZIP compression, InstantMessaging, and even e-business (EDI) transactions. .NET, Java, COM, C++, Delphi,everything is included, together with per developer licensing, free quarterly update CDsand free upgrades during the subscription term.Paradise #

    D77 09101L01 $1,444.99 programmers.com/faircom

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

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

    including Windows, UNIX, Linux, and Mac OS X

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

    Paradise # F01 0131

    $711.99

    programmers.com/vmware

    View PremierParadise #

    V55 66101A01

    CALLI

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

    VDI Included

    New Release!

    programmers.com/mindjet

    for Windows 1 User

    Paradise # F15 17301A02

    $299.99

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

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

    Paradise # I0M 02501F01 $1,033.99

    programmers.com/acresso

    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 standards,InstallShield Professional makes your life easy by letting you take advantage of latesttechnologiesincluding full support forWindows Vista.

    Paradise # I21 02201A01 $1,689.99

    programmers.com/infragistics

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

  • Editors Note

    BY PATRICK MEADEReditor in chief

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com6

    CALCULATING THE COST OF CHANGEI hate doing something twice, especially if I perceive that redoing somethingisor should beunnecessary.Sometimes a portable USB storage device givesout or a file gets corrupted,and I find myself needing to reproduce content orredo an edit Ive already done.It doesnt happen often,but it hap-pens,and 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 file.Will it open in notepad, perhaps? Will a different USB port beable to see the portable storage device? Experience tells me Imbetter off knuckling down and just getting to work,but Im 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 dont wantsympathy or empathy at such times. No, I want to break stuff,to throw the offending computer out the window. I want tosmash things.

    Given how much I hate to redo stuff, I know one thingdefinitively: Id 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 Ive ever donebecause of far-reaching changes would mean a weeks-, if notmonths-long stream of invectives to make David Mametblush. Id be in a semi-permanent rage state, tucked away in aback office or closet so no one else would have to listen to me.Its one thing to redo something because I made an error; itsquite another to be forced to redo something because some-one else makes a change thats in my best interests,especiallyif 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, WindowsWorkflow Changes Direction, 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 3.5 applications, and urged that you put offdeveloping new WF-based applications if you havent 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 months Letters to the Editor include a response toDollards article from Matt Fritz. Fritz laments the changes toWF, as well as other, similar types of changes that hes experi-enced as a Microsoft developer (see Running the DevelopmentTreadmill, p. 8). Fritz notes that hes a strong believer in theMicrosoft development platform,but goes on to say that using[developers] as beta and field testers aint right. It costs us andour companies time and money.

    Hes 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 wontprovide the same return,whether because the developer doesntneed the changes, or because the changes mean abandoning aplatform or technology theyve invested considerable timeand energy learning and deploying.

    One positive aspect of the changes to WF is that theyreoccurring before the product matured. Another positiveaspect: WF is not a technology thats in widespread use, andthe current implementation is lacking in significant ways thatthe next version will address. Theres a reason more peopledont use it now.

    But what if youre 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. Its penalizing its own best,most enthusiastic customersthe people, in fact, who hadpaid money for WF.When discussing Microsofts approach toWF with a couple advisors to VSM, the conversation wouldusually start with Big Bad Microsoftfor doing this to its cus-tomers but eventually would swing back to discussing why PH

    OT

    O B

    Y P

    AT

    JOH

    NS

    ON

    ST

    UD

    IOS

    0209vsm_EdNote_6-8.v5 1/22/09 1:42 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 ESRI Developer Network (EDNSM), you have access to the complete ESRI

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

    every platform. Whether youre a desktop, mobile, server, or Web developer, EDN provides the

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

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

    Subscribe to EDN and leverage the power of GIS to get

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

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

  • E D I T O R S N O T E > > C O S T O F C H A N G E

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com8

    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 product.Weall know the adage that you shouldnt adopt a pre-version 3product from Microsoft, but we dont actually mean it, do we?Regardless, that argument shouldnt be in play here: Microsoftis scrapping a version 3.5 product. The product hadntachieved maturity, nor had it achieved widespread acceptance,but it seems unlikely you could see this coming if you were acompany that relied on WF.

    The changes that are occurring in WF wouldnt seem sosignificant if there werent other examples of developers hav-ing to rework their applications because Microsoft madechanges of a similar scope in other technologies. For example,the introduction of a .NET version of VB roiled the VB com-munity for years, and were 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 3.5apps 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 on,whether 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 youre doing now for something else.

    Im 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 theres a cost to backward compati-bility, especially in terms of application performance.As muchas I hate to redo things or have to rework things to achieve functional equivalence, Im willing to accept changes that breakhow things work now in exchange for a significant improve-ment in how things will work going forwardespecially whenthe reason for the change is compelling.

    But the central issue is this: My notion of compellingdoesnt always match that of the softwares designers. Whatstrikes a software developer as essential can strike me as capri-cious (Microsoft Offices 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 dont carehow much the first group wins if the software becomes unus-able for me. Thats part of the equation that a company thatcreates software must consider.When a company bets Ill 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 own.And Id like a company that places bets with my money to doso at least as conservatively as I would. In the case of WF,Microsoft isnt just betting with other peoples money; its 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, its 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 its 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 anadmittedly less dramaticeffecton 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 unannounced,to 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 [email protected] [email protected].

    The product hadnt achieved maturity, nor had it achieved widespread acceptance, but it seems

    unlikely you could see this coming if you were a company that relied on WF.

    0209vsm_EdNote_6-8.v5 1/22/09 1:42 PM Page 8

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

    ONLINE

    www.visualstudiomagazine.com

    Project13 9/18/07 3:34 PM Page 1

  • VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com10

    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 form,fit, 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, c/oVisual Studio Magazine, 230 CaliforniaSt., San Francisco, CA 94111; faxthem to 415-814-0961; or e-mailthem to [email protected].

    Letters

    Running the Development Treadmill

    Kathleen Dollards article on the changes in the upcoming version of Workflow [AskKathleen,Windows Workflow Changes Direction, January 2009] reminded me that thesame thing happened with SQL Server DTS 2000/2005, as well as with the MapPointobject 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?

    Im 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 aint right. It costs us and our companiestime and money. Now I have Biztalk, Windows Communication Foundation, WindowsWorkflow, and LINQ on the wait-and-see 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 couldnt see whenthey started doing things wrong, like DEC, Wang, and Novell (and now General Motors?). Itsa mistake to alienate the developer community. Every company hasor will havea 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 Wagners 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 VB.NET functionality, so that we couldhave gotten a clue as to what the differences are and why we should care [C# Corner, WhatVB Devs Should Know About C#, December 2008]. As it is, this read more like a things I liketo do in C# article than an aid for folks trying to bridge the gap between VB.NET and C#.

    Bill Clardy, Orange, Calif., originally posted online

    Correction:The recent First Looks review of Compuwares DevPartner Studio contained an error whendiscussing the capabilities of that tools Performance Analyzer [Understand What Your AppDoes, January 2009]. Performance Analyzer can be configured to analyze ASP.NET applicationsrunning on both local and remote computers. You can read an updated version of the reviewonline at VisualStudioMagazine.com that explains the general steps you need to take to usePerformance Analyzer with ASP.NET. Locator+ code: VS0901FL

    VSM regrets the error.

    VisualStudioMagazine.comFebruary 2009 Volume 19 No. 2

    Editorial StaffVice President, Doug Barney

    Editorial DirectorEditor in Chief Patrick Meader

    Managing Editor Guy WrightManaging 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 ShultzGraphic Designer Erin Horlacher

    Online/Digital MediaEditor, VisualStudio Becky Nagel

    Magazine.comExecutive Editor, New Media Michael Domingo

    Online News Editor Kurt MackieAssociate Editor, Web Gladys Rama

    Web Producer Shane LeeDirector, Web Development Rita Zurcher

    President Henry AllainVice President, Publishing Matt N. Morollo

    Director of Marketing Michele ImgrundOnline Marketing Director Tracy S. Cook

    Marketing Programs Manager Videssa Djucich

    President & Neal VitaleChief Executive Officer

    Senior Vice President Richard Vitale& Chief Financial Officer

    Executive Vice President Michael J. ValentiPresident, 1105 Events Dick Blouin

    Vice President, Finance Christopher M. Coates& Administration

    Vice President, Audience Abraham M. LangerMarketing & Web Operations

    Vice President, Information Erik A. LindgrenTechnology & 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 VisualStudioMagazine.com.

    E-mail: E-mail is routed to individuals desktops. Please use thefollowing form: [email protected]. Do not include a middle name or middle initials.

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

    San Francisco Office 415-814-0950; Fax 415-814-0961Irvine Office 949-265-1520; Fax 949-265-1528Corporate 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_10.v7 1/22/09 1:37 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 ADO.NETDataDirect Technologies has released DataDi-rect Connect for ADO.NET data providers. WithDataDirect Connect for ADO.NET, 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 database,new 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 Server,and Sybase databases, without having todeploy and load client libraries.

    The suite of ADO.NET data providers usesa 100 percent managed code architecture,therefore DataDirect Connect for ADO.NETeliminates 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 ADO.NET developers get full sup-port for .NET Framework.

    The latest release of DataDirect Connectfor ADO.NET additionally offers performanceenhancements including additional tuningoptions that support a variety of applicationperformance scenarios and statement caching,a connection option that requires no changesto the application and can increase the effi-ciency of applications connecting to Oracle,DB2, and Sybase.

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

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

    DataDirect Connect for ADO.NET

    DataDirect Technologies

    Price: Contact vendor for pricing

    Web: www.datadirect.com

    Phone: U.S.: 800-876-3101;

    World: 44 (0) 1753 218 930

    List & Label 14Combit has released version 14 of its report-generating software List & Label. Among thenew features is the inclusion ofa real-data-preview, so changescan now be seen with real data,without having to leave theDesigner. Within the previewtheres also an integrated indexto ease navigation through thereport. Additionally, its 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 List& 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 2009.Additionally, 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 & 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

    VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE 11

    0209vsm_FirstLooks_11-13.v7 1/22/09 1:39 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 & Label can be integrated into alarge variety of programming languages.

    List & Label 14

    Combit GmbH

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

    sional starts at 1,380 euro; and Enterprise at 2,094 euro.

    Web: www.combit.net/en

    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 3.5. Major enhancements to the suite include addingTouch functionality to all controls and a new graphical user interface.Adding 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 SmartGrida grid con-trol with built-in auto edit capabilities, Touch scroll support, and theability to save different SmartGrid layouts to XML files; AdvancedLista 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-pactCharta charting control with five chart types including Pie, Bar,Line, Doughnut, and Area charts; OutlookWeekCalendar and Outlook-MonthCalendarday/week and month/year appointment schedulingcontrols; OutlookDateTimePickera modern version of a common con-trol providing advanced styles; DetailViewfor creating mobile userinput forms where input controls are collected in a compact environ-ment giving the form standard Windows Mobile look and feel; InkBoxan ink control suitable for quick notes or signatures; ImageBoxanimage control supporting various graphic formats; CustomKeyboardaflexible control supporting custom keyboard layouts; OutlookShortcut-Bara 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 http://tinyurl.com/9wukrz.

    MobileForms Toolkit 2009

    Resco

    Price: Standard Edition $499.95, Professional Edition $999.95,

    Enterprise Edition $1,999.95

    Web: www.resco.net

    Fax: +421 2 090 2010

    Editors Note: Please send product information to New Products Editor, c/oVisual Studio Magazine, 230 California St., San Francisco, CA 94111; Phone:

    415-814-0950, fax: 415-814-0961; e-mail [email protected].

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

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

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

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

    Contact dtSearch for fully-functional evaluations

    The Smart Choice for Text Retrieval

    since 1991

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

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

    For combing through large amounts of data, dtSearch leads the market Network Computing

    dtSearch covers all data sources ... powerful Web-based engines eWEEK

    dtSearch searches at blazing speeds Computer Reseller News Test Center

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

    Instantly SearchTerabytes of Text

    Network with Spider

    Network withSpider

    Web with Spider

    Web with Spider

    Desktop with Spider

    Desktop withSpider

    Network with Spider

    Web with Spider

    Publish for CD/DVDs

    Publish for CD/DVDs

    Publish for CD/DVDs

    Desktop with Spider

    Engine for Linux

    Engine for Linux

    Engine for Linux

    Engine for Win & .NET

    Engine for Win & .NET

    Engine for Win & .NET

    New64-bitNew64-bit

    0209vsm_FirstLooks_11-13.v7 1/22/09 1:39 PM Page 12

  • VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE 13

    MMadCap Flare 4.1 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 familiar,integrated environment that organizes files, flagserrors, assists with testing and reporting, controls thebuild process, and generally makes them more efficient.Flare 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 pagesforexample, legal disclaimersin 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 projects 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 doesnt generatefiles that integrate with Visual Studios help collections (MS

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

    Source control is essential for programmers and writers alike.When you create a Flare project, theres 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 Vaultprovidera real bonus. That said, the IDE crashed when I tried tocancel out of a Vault connection using the Advanced option.

    Youll appreciate the small conditional-text touches likeautomatically adjusting cross-references for the medium. Forexample, in a PDF you might generate as shown on p. 32where the HTML version, which doesnt use page numbers,would substitute a hyperlink.

    MadCaps 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 youor the IT departmentunblock its stealth access. With product announcements thatstart with Dear Propeller Heads! the folks at MadCap seemfriendly, fun, and upfront. Thats why a high-handed licensingapproach is disappointing and out of character. VSM

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

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

    REDUCE KEYSTROKES AND WRITERS CRAMP You can store frequently used resources as snippets in MadCap Flare 4.1. 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 4.1MadCap SoftwareWeb: www.madcapsoftware.comPhone: 858-320-0387Price: $899Quick Facts: Integrated development environmentfor authoring user manuals, online help, and Webpages. Generates multiple output formats from a single XML source.Pros: File linking and conditional text; XML editor;IntelliSense support; drag-and-drop snippets; source-control friendly; command-line mode; built-in .PDFand .XPS generators; valuable user assistance.Cons: Doesnt 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-13.v7 1/22/09 1:39 PM Page 13

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

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com14

    cloud computing. Microsofts cloud candidateWindows Azureoccupied the bulk of OzziesDay One PDC keynote and was the subject of 39sessions, more than twice as many as the next-most-discussed topicVisual Studio. WindowsAzure is an Internet-facing operating system thatpromises to enable .NET developers to leveragetheir current ASP.NET,Windows CommunicationFoundation (WCF),and Windows Workflow pro-gramming skills to deploy .NET Web applicationsto Microsofts newly built data centers quickly andeasily. Microsofts message to VS developers is touse your existing tools, knowledge, and skill setfor projects you deploy to Windows Azure.

    The Azure Services Platform, for which theWindows Azure OS serves as the foundation,provides massively scalabletable and blob storageservices, a persistent message-queue service, sev-eral .NET utility services (formerly code-namedZurich), a Live operating environment, and thesuccessor to SQL Server Data Services thats nowcalled SQL Data Services (see Figure 1, oppositepage). Ill give you a brief introduction to theplatforms objectives and its architectural detailsto achieve them, and describe how Azure differsfrom its cloud-based competitors. Then Ill drilldown into programming data-intensive Webapplications that take advantage of Azures

    The three-year hiatus between the Microsoft ProfessionalDevelopers Conference (PDC) 2008 and its 2005 predecessorgave Ray Ozzie and his newly expanded development teamthe opportunity to play catch-up with Amazon.com Inc., Google Inc.,and 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, ASP.NET, and the Azure Services Platformcombine to simplify local development of data-intensive Webapps and automate their deployment in Microsoft data centers.The 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

    VB.NET

    C#

    SQL Server

    ASP.NET

    XML

    Other: Azure ServicesPlatformElastic ComputeCloud (EC2)

    0209vsm_F1Retire_14-25.v13 1/22/09 1:41 PM Page 14

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

    VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE 15

    ILLU

    ST

    RA

    TIO

    N B

    Y R

    AN

    DY

    LY

    HU

    S

    unique development and deployment tools. Finally, Ill discuss aninstrumented ASP.NET 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 BlobServices,Queue Services,SQL Data Services, and .NET Services.

    Cloud computing 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 SalesForce.com 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 AWSAzures 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 applications,and Elastic Block Store to persist other instance data(see Table 1, p. 23, and Additional Resources, p. 25).Amazon EC2 running Windows Server and SimpleDBare in the beta-testing stage, as is the Google AppEngine (GAE). Microsoft wont reveal pricing forAzure services until later in 2009 when version 1 is

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

    FIGURE 1 Move ASP.NET Web Apps to the Cloud The foundation for the AzureServices Platform is the Windows Azure operating system, which provides the fabricfor virtualized Windows 2008 Server instances; schemaless persistent table, blob,and 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-25.v13 1/22/09 1:41 PM Page 15

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

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com16

    Windows Azure runs on Windows Server 2008 with virtual-ization provided by Microsofts Hyper-V hypervisor technologyto deliver a runtime fabric that handles load balancing, datareplication, and resource management. According to MicrosoftsErick Smith, the Azure Fabric Controller maintains a graph ofthe inventory of physical and virtual machines, load balancers,routers, and switches it manages in a Microsoft data center. Edgesof the graph are interconnections of various types, for example,network, serial, and power cables. You specify the topology ofyour servicethe number and connectivity of roles, the attrib-utes and locations of the various hardware components, as wellas the numbers of fault/update domains and maximuminstances of each role you need with a declarative Service Model.In 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 fabrics 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 Python,Ruby, 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).Ultimately,youll be able to specifyyour Service Model with Oslos domain-specific language tools andstore the model in the Oslo repository.

    The current CTP released at PDC 2008 doesnt 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 ASP.NET Web application runningon IIS 7 instance(s) under Windows Server 2008 (see Figure 3,opposite page). Windows Azure doesnt support file-system Web

    site projects. Worker Roles are asynchronous 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. Azures October 2008 CTP limits testers to amaximum of 2,000 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 dontneed 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 Prompt,and Windows Azure SDK Documentation nodes.Choosing the Development Fabric and Develop-ment Storage nodes or clicking their icons in theTaskbars Notification Area opens managementdialogs for the two service emulators (see Figure 4,p. 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 theaccounts public Production URL (see Figure 6, p. 22).

    0209vsm_F1Retire_14-25.v13 1/22/09 1:41 PM Page 16

  • VisualStudioMagazine.com February 2009 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-figuration.cscfg and ServiceDefinition.csdef files, as well as anASP.NET Web Role application. You also must expand the Win-dows Azure SDKs \Program Files\Windows Azure SDK\v1.0\sam-ples.zip file to a temporary folder. Then add the \Temp\Storage-Client\ Lib\StorageClient.csproj and \Temp\HelloFabric\Com-mon\Common.csproj 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 Microsoft.ServiceHost-ing.ServiceRuntime.dll 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 ASP.NETprojects or create a new Web application fromscratch.

    Settings in the ServiceConfiguration.cscfg filedetermine whether your application uses local orcloud storage when emulating the hosted service.Heres a ServiceConfiguration.csfg file with entriesfor both local and cloud storage with AccountSh-aredKey values abbreviated:

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

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com18

    -->

    Settings for cloud storage services are commented out in the preceding example; local setting values are the same for all users.The element causes three instances to run in the Development or Azure Fabric. Note that the preced-

    ing 127.0.0.1 (localhost) port numbers appear in Figure 4sDevelopment Storage dialog. YourPrimaryAccessKey is thebase64Encoded Primary Access Key value on the Azure PortalsProject Summary page.

    Each element in the Ser-viceConfiguration.csfg file must have a corresponding entry in theServiceDefinition.csdef file (indicated here in red):

    If the element name attribute values dontmatch in the two files, you receive an Invalid configu-ration file message when running in the DeveloperFabric; the Azure Fabric adds the names of missing ormisspelled elements. Thematching name attributes requirement ishidden in an Issues and Constraints in the WindowsAzure Tools and SDK white paper (see AdditionalResources, p. 25). The elementsport attribute determines whether Azure expectsclear-text HTTP or encrypted HTTPSSecure Sock-ets Layer (SSL)protocol. Setting up HTTPS requirescompleting the entries on the SSL page of the Project-Name nodes 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 thats related to Googles 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 articles SampleWebCloudService project running in the Development Fabric and emulated Azure Storage Services for blobs, queues, and Azures 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 VSs compile andrun operations significantly.

    0209vsm_F1Retire_14-25.v13 1/22/09 1:41 PM Page 18

  • VisualStudioMagazine.com February 2009 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) CTPs 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 thats related to Googles Bigtable, and Microsoft says Azure tablesare designed to scale to billions of entities and terabytes of data. Azure and SDS table versions offerfree-form open properties (formerly flex proper-ties) or property bags and permit adding or remov-ing table attribute/value 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, DateTime,Double, 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. MyComparing Google App Engine, Amazon SimpleDB,and Microsoft SQL Server Data Services 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 10GB.Azure 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 doesnt specify the inconsistentwindows 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 at some point in the future per-form atomic transactions across multiple entities within thesame partition. Partitions are similar to Bigtables tablets withsome characteristics of the App Engines 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 PartitionKey/RowKey order; inequalityfilters and developer-specified secondary indexes for alternativesorting orders are slated for the release version.

    Progress Toward StandardsMicrosofts data-access teams are moving to standards-basedRESTful data access protocols at an increasingly rapid pace.Azure 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 ADO.NETData Services (Astoria) runtime, which supports open prop-erties with the Atom syndication wire protocol and operateswith the existing ADO.NET Data Services client libraries andtools. Pablo Castros ADO.NET Data Services in WindowsAzure: pushing scalability to the next level blog post describeshow the Astoria team modified the runtime to accommodate adynamic open properties 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 entities.Heres the GET request header for the second page of the sampleprojects Customers GridView, which starts with CENTC as theCustomerID and RowKey value:

    FIGURE 5 Stage Azure Apps for Testing before Production DeploymentWindows Azures Click-Twice deployment approach lets you test your project ina Staging instance with a private guid.cloudapp.net URL before placing it in pro-duction with your AccountName.cloudapp.net URL. Right-clicking on the Project-Name service node and choosing Publish opens a page that lets you browse foryour project ProjectName.cspkg package and ServiceConfiguration.cscfg files inthe projects \ProjectName\bin\Debug\Publish 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-25.v13 1/22/09 1:41 PM Page 19

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

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

  • GET /CustomerTable()?$top=12&NextPartitionKey=Customer&NextRowKey=CENTC HTTP/1.1

    User-Agent: Microsoft ADO.NET Data Servicesx-ms-date: Fri, 19 Dec 2008 23:37:31 GMTAuthorization: SharedKeyLite oakleaf:Z/KA 5Yc=Accept: application/atom+xml,application/xmlAccept-Charset: UTF-8DataServiceVersion: 1.0;NetFxMaxDataServiceVersion: 1.0;NetFxHost: oakleaf.table.core.windows.net

    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 headers 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 23:37:31 GMT\n/oakleaf/Tables

    Queries return a maximum of 1,000 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. Heres the GET response header and abbreviated bodyof the second GridView page:

    HTTP/1.1 200 OKCache-Control: no-cacheContent-Type: application/atom+xml;charset=utf-8Server: Table Service Version 1.0 Microsoft-

    HTTPAPI/2.0x-ms-request-id: 2a109a5d- f6ex-ms-continuation-NextPartitionKey: Customerx-ms-continuation-NextRowKey: FRANKDate: Fri, 19 Dec 2008 23:37:00 GMTContent-Length: 15691

    CustomerTable

    http://oakleaf.table.core.windows.net/

    CustomerTable

    2008-12-19T23:37:01Z

    http://oakleaf.table.core.windows.net/

    CustomerTable(PartitionKey='Customer',RowKey='CENTC')

    2008-12-19T23:37:01Z

    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 articlesSampleCloudWebService.sln project in the Azure Services Platform CTP atoakleaf.cloudapp.net. The Default.aspx 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 projects 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 February 2009 VisualStudioMagazine.com22

    0209vsm_F1Retire_14-25.v13 1/22/09 1:41 PM Page 22

  • VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE 23

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

    CustomerCENTC

    2008-12-19T22:10:30.2752Z

    Sierras de Granada 9993

    Mxico D.F.

    Centro comercial Moctezuma

    Francisco Chang

    Use LINQ to REST to Query TablesADO.NET Data Services enables a subset of the LINQ StandardQuery Operators to compose LINQ queries, which an expressiontree translates to an HTTP URI. The StorageClient librarysTableStorage, TableStorageDataServiceContext, and TableStor-ageDataServiceQuery classes and TableStorageEntity abstractclass handle interaction with the ADO.NET Data Services clientlibrary (System.Data.Services.Client) 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 Page.Preload 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 1.5 - 1.7 GHz x64 equivalent 1.7GHz

    Memory 1.7GB 1.75GB

    Network 100Mbps 250Mbps

    Transient storage 250GB 160GB

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

    Authentication/Authorization

    NET Access Control: LiveID, username/ pass-word, X.509 certs, Information Card

    Windows with Authentication Services (surcharge)

    TABLE 1 Compare Windows Azure October 2008 CTP and Amazon EC2 with Windows Server Beta On Sept. 30, 2008, Amazon.com Inc.announced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003. The default AmazonMachine Image (AMI) creates a 32-bit small instance with IIS, .NET 2.0 SP1, 3.0 SP1, and 3.5 (not SP1), and SQL Server Express 2005. 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-25.v13 1/22/09 1:41 PM Page 23

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

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com24

    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 Microsofts Steve Marx

    var query = (DataServiceQuery)(new CustomerDataServiceContext(account).CustomerTable.Take(12));

    // Get the continuation tokens from the requestvar cTokens = Request["ct"];if (cTokens != null){

    // ct parameter format is "/"string[] tokens = cTokens.Split('/');var partitionToken = tokens[0];var rowToken = tokens[1];

    // These QueryOptions become continuation// token query parameters in the requestquery = query.AddQueryOption(

    "NextPartitionKey", partitionToken).AddQueryOption("NextRowKey", rowToken);

    }// Execute the LINQ to REST queryvar result = query.Execute();

    // Cast result to a QueryOperationResponsevar qor = (QueryOperationResponse)result;

    // Get the continuation token valuesstring nextPartition = null;string nextRow = null;qor.Headers.TryGetValue(

    "x-ms-continuation-NextPartitionKey", out nextPartition);

    qor.Headers.TryGetValue("x-ms-continuation-NextRowKey", out nextRow);

    if (nextPartition != null && nextRow != null){

    // Add the continuation tokens to the GET querynextLink.NavigateUrl =

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

    }// Set the customersView DataView's DataSource // to the query resultcustomersView.DataSourceID = null;customersView.DataSource = result;customersView.DataBind();

    }

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

    StorageAccountInfo account = StorageAccountInfo.

    GetDefaultTableStorageAccountFromConfiguration();TableStorage.CreateTablesFromModel

    (typeof(CustomerDataServiceContext), account);

    After debugging your project in the SDKs local Developer fabric,copy the ApplicationID from the Live Services and Active Direc-tory Federation section of the Azure Services Development Portalto the Portal page of the CloudService nodes Properties sheet,right-click on the node, and choose Publish to open a windowcontaining your projects \bin\Debug\Publish folder. Click onDeploy in the Manage pages Staging area to open the StagingDeployment page, browse to the ProjectName.cspkg and Service-Configuration.cscfg 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 5,p. 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 accountname.cloudapp.net URL (see Fig-ure 6, p. 22).ClickTwice (once for Staging, once for Production)deployment of roles to the Azure Fabric is a snapand much eas-ier than migrating apps to AWS or the GAE.

    SDS vs. AzureTheres 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

    Theres considerable overlap of Azure Table Services and SDS features, which portends a future

    conflict at least as serious as that between LINQ to SQL and the Entity Framework.

    0209vsm_F1Retire_14-25.v13 1/22/09 1:41 PM Page 24

  • VisualStudioMagazine.com February 2009 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 ADO.NET 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 Kakivaya,Among 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 queries.

    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 $0.60 to $1.20 perinstance-hour surcharge for SQL Server 2005 Standard. (SQLServer 2005 Express comes free with the $0.125 to $1.20 hourlycharge for Windows Server 2003 R2 instances.) Amazons sur-charge for Windows Authentication Services is $0.25 to $0.60 perinstance-hour, depending on instance type. That totals $7,344 to$15,552 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 plans.VSM

    Roger Jennings is an independent data-oriented .NET developer andcomputer book author with more than 1.25 million English copies inprint. His books on Microsoft operating systems and data technologieshave been translated into more than 20 languages. Jenningss latestbook is Professional ADO.NET 3.5 with LINQ and the EntityFramework (WROX/Wiley 2009). Hes also a Visual Studio Magazinecontributing editor and writer for Redmond Developer News, andmanages the OakLeaf Systems blog (oakleafblog.blogspot.com). Youcan reach him at [email protected].

    ADDITIONAL RESOURCES:

    Azure Services Platform homepage: tinyurl.com/6lr5nr

    MSDN homepage for Azure developers: tinyurl.com/65ogcw

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

    Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)download: tinyurl.com/58oega

    Azure Services Training Kit - PDC Preview download: tinyurl.com/5z87ru

    Register with Microsoft Connect to access Azure services online:tinyurl.com/5urpnv

    Setting Up the Windows Azure Services Platform: An Illustrated Walk-through OakLeaf blog post: tinyurl.com/65wywn

    Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video(Channel9): tinyurl.com/5tsgvm; transcript: tinyurl.com/5vhprm

    Video clips of 39 Azure-related sessions at PDC 2008 (Channel9):tinyurl.com/5vd7cr

    Video clips of eight SQL Data Services-related sessions at PDC 2008(Channel9): tinyurl.com/638uoo

    Azure SDK online documentation: tinyurl.com/6yy75b

    SQL Services Labs home page with planned incubation projects for SDStinyurl.com/5asfdm

    Windows Azure TablesProgramming Table Storage white paper:tinyurl.com/59tlo7

    Windows Azure TablesProgramming Blog Storage white paper:tinyurl.com/6785ra

    Issues and Constraints in the Windows Azure Tools and SDK whitepaper tinyurl.com/4m92h9

    The Atom Syndication Format (1.0) specification (IETF RFC 4287):tinyurl.com/ysewpe

    Amazon Elastic Compute Cloud (EC2) Running Microsoft Windows Serverand SQL Server (Beta) data sheet: tinyurl.com/4xw9cw

    Amazon Elastic Compute Cloud (Amazon EC2) data sheet:http://tinyurl.com/4bw86s

    ADO.NET Data Services in Windows Azure: pushing scalability to the nextlevel blog post by Pablo Castro tinyurl.com/4ky4x2

    Comparing Google App Engine, Amazon SimpleDB and Microsoft SQLServer Data Services OakLeaf Systems blog post: tinyurl.com/626td8

    Test Harnesses Compare Amazon EC2 with SQL Server and SimpleDBPerformance OakLeaf Systems blog post: http://tinyurl.com/5ea99x

    SQL Data Services (SDS) Test Harness Updated to the Windows AzureServices Platform OakLeaf Systems blog post: tinyurl.com/58tw7c

    Test-Drive SQL Server Data Services by Roger Jennings: Locator+ CodeVS0807RJ_T

    Manipulate Data in the Cloud by Roger Jennings: Locator+ CodeVS0805RJ_T

    GO ONLINE

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

    READ & 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-25.v13 1/22/09 1:41 PM Page 25

  • Ive 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 methods parameters contain theSystem.Delegate abstract type, using lambda expressions introduces special problems: The C#

    compiler cant convert a lambda to some not-yet-defined concrete, derived delegate type.Without some extra thought on your part, youll end up with code that looks like it came from

    .NET 1.0. Ill walk you through the exercise of understanding why lambda expressions arent immediatelyconvertible to abstract delegate types, and how you can convince the compiler to convert the specificdelegate type you defined for your use. The solution Ill describe relies on Windows Presentation Foundation (WPF) and the System.Windows.Threading.Dispatcher component, but this is not strictlya WPF issue. The issue described crops up in several locations in the .NET Framework, including theWindows Forms, Office APIs, and Reflection APIs.Youll 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 thats some form of delegate, Iprefer to use a lambda expression instead of a more verbose representation. For example, this line of codecreates a System.Windows.Threading.Timer that calls the method TickHandler when the timer fires:

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

    TECHNOLOGY TOOLBOX

    VB.NET

    C#

    SQL Server

    ASP.NET

    XML

    Lambda expressions arenothing more than convenient syntax for delegates. So why cant youuse them where the Framework expects a delegate? And more importantly, what can youdo about it?BY 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 February 2009 VisualStudioMagazine.com26

    ILLU

    ST

    RA

    TIO

    N B

    Y I

    ST

    OC

    KP

    HO

    TO

    .CO

    M

    0209vsm_C#Corner_26-29.v8 1/22/09 1:43 PM Page 26

  • C # C O R N E R U S I N G E X P R E S S I O N S

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com 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 time,but the same technique doesntwork when the API uses System.Delegate as a parameter.For example,you use the System.Windows.Controls.Dispatcher.Invoke() methodto marshal calls across threads in WPF:

    public object Invoke(delegate method,params object[] args)

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

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

    You get the cryptic error:

    error CS1660: Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type

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

    I built a WPF timer application to show you how this works,illustrating how a little C# 3.0 can make it easy to work with 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 youllrun 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 control.Thats a couple quick lines of code:

    MyTime.Background = newBrush;MyTime.Content = label;

    The timer runs on a background thread, so you need to marshal thecall across the thread boundary using the Dispatcher.Invoke()method. These two lines of code are what youd want to put in alambda expression, not the heavy-duty business logic that justifies amethod definition.But I said earlier that a lambda doesnt work withDispatcher.Invoke. It can, but you need to use a concrete delegatedefinition. Several are defined in .NET Framework 3.5. The fact thatyou can use the built-in delegate definitions and assign them makesthis solution less work than might initially appear to be the case.These 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:

    Action updateTimer;

    After declaring the variable,you can assign the delegate variable to thebody of the code you want to execute.You can use a lambda expres-sion here because Action is a concrete delegate definition:

    updateTimer = (label, newBrush) =>{

    MyTime.Background = newBrush;MyTime.Content = label;

    };

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

    Whenever youre not sure what thread youre on, you can call Dispatcher.CheckAccess() 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. Its a great way to democross-thread calls, because the timer runs in a background thread.

    0209vsm_C#Corner_26-29.v8 1/22/09 1:43 PM Page 27

  • C # C O R N E R U S I N G E X P R E S S I O N S

    VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com28

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

    MyTime.Dispatcher.Invoke(updateTimer, newLabel, next);

    }

    elseupdateTimer(newLabel, next);

    This process is straightforward, but its something that youll dorepeatedly, so lets go a few steps further and make this easier to reuse.

    Theres a simple pattern at work here.Event handlers can be called from a back-ground thread.Youll see this behavior whenyou use timers, when you call Web servicesasynchronously,and in other common tasks.Whenever youre not sure what thread youreon,you can call Dispatcher.CheckAccess() todetermine whether you can access any UI con-trols. If you need to marshal a call acrossthread boundaries, you must useDispatcher.Invoke().The Dispatcher.Invoke()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 delegate.You want that method toappear as if it were a member of the Sys-tem.Windows.Controls.Control class. Thisenables you to use the code as if it were partof any control. C# 3.0 gives you a way to dothis: extension methods. You need to write afew different overloads of the methods,whichenables you to use them with different num-bers of parameters:

    public static class WPFExtensions:

    {public static voidInvokeIfNeeded(this Control widget, Action whatToDo)

    {if (!widget.Dispatcher.

    CheckAccess())

    widget.Dispatcher.Invoke(whatToDo);else

    whatToDo();}

    public static void InvokeIfNeeded(this Controlwidget, Action whatToDo, T parm)

    Develop your application with the same robust imaging technologies used by Microsoft,HP, 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.

    Image Formats: All industry standardsincluding TIFF, EXIF, PDF, JPEG/JPEG2000,DICOM, PCL, DWG and hundreds more.Image Compression: From standardJBIG, JBIG2, ABIC, JPEG and CCITT G3/G4 toLEADs specialized ABC, CMP and CMWcompression.Display Controls: Scroll, zoom, pan,magnify glass, brightness/contrast/gamma,window level.Image Processin