Where Have All the Coders Gone? VisualStudioMagazine.com
E N T E R P R I S E
S O L U T I O N S
F O R
.N E T
D E V E L O P M E N T
RET ETIR IRE E YOU OUR R Use Azure Az ure Services to Maximize M aximize Availability, Availability, Reliability,, and Scalability. Reliability
DATA CEN CENT TER PLUS
Use Lambda Expressions for Abstract Delegates Use Iterators in VB
2 . o N , 9 1 . l o V • 9 0 0 2 Y R A U R B E F
Be BeT The heD DataGuru
V i s ua l St ud io
W P F/ Si lv er li ght
S h a re P o in t
S QL Server
Ja va
CO M
P ow e r S h e l l
Ach chieve ieve A Hi Higher gher State Of DataV taVisuali isualizat zatiion To master To master the the art art of data visua visualizat lization, ion, you must must seek seek out the the leader leader.. For almost two decad decades, es, Software FX has risen above all others by bringing top-of-the-line data visualization tools to enterprise developers working with diverse markets, platforms and environments. environments. This wisdom has evolved into a vast body of products, including a data presentation tool that provides a best-of-breed solution for Windows developers seeking enterprise quality and performance, as well as a professional IT monitoring solution offering incredible incredible features for reporting and monitoring data. For a world of data visualization products that can raise your work to a higher level, depend on the source that’s clearly on top. Our most popular product, Chart FX provides provides charts, gauges and maps with additional vertical visualization functionality functionality for business intelligenc intelligence e (OLAP), geographic data, financial technical technical analysis, and statistical statis tical studies and formulas. Recogniz Recognized ed as the innovat innovator or and leader leader of the charting component catego cat egory ry for for the past past 15 year years, s, Char Chartt FX delivers incomparable incomparable galle gallery ry option options, s, aesthetics aesth etics and data analysis features. Grid FX was speci Grid specifical fically ly design designed ed for visua visuall studio developers to take advantage of a powerful design-time experience, integrated Chart FX functional funct ionality ity right in the box, and AJAX to provide robust, run-time functional functionality ity in ASP.net applications. The dynamic aesthetic features for data presentation presentation and analysis allow simple adaptation adapta tion to an existi existing ng applicat application ion or to speci specific fic corporate branding guidelines. PowerGadgets puts powerful IT monitoring PowerGadgets on your desktop and in your data sidebar. sidebar. IT pro profes fessio sional nals s can now cr creat eate e gad gadget gets s that consume data from WMI, Exchange, SQLServer SQLServ er and eve even n theWind theWindowsRegis owsRegistry try.. PowerGadgets does not require any developmen devel opmentt envir environme onments,servers nts,servers or browsers brows ers to run real real-ti -time me gadget compo components nents such as charts, gauges and maps.
Visitt softw Visi softwaref arefx.co x.com m for inte interact ractive ive demo demos s and more info informat rmation ion abou aboutt our late latest st prod products ucts..
Data visualization for every need, every platform
Contents Fe b r u a r y 20 20 0 9 • VO L U M E 19 19 • N O . 2
COLUMNS C# CORNER
26 Use Lambda Expressions
for Abstract Delegates Lambda expressions are nothing more than convenient syntax for delegates. So why can’t you use them where the Framew Framework ork expects a delegate? And more importantly, what can you do about it? BY BILL WAGNER ON VB
32 Use Iterators in VB Now Iterators are a crucial part of modern programming, not least because they provide the basis for collection traversa traversall using For Each loops. Learn how to take advantage of them in your code with several different techniques for creating your own iterators in VB. BY BILL MCCARTHY
14
DEPARTMENTS
6 Editor’s Note FEATURES
BY PATRICK MEADER
10 Letters to the Editor
14
Retire Visual Studio 2008,Your ASP.NET,Data and the Center Azure Services Platform combine to simplify local development of data-intensive Web apps and automate their deployment in Microsoft data centers. The result: You get maximized availability and reliability with almost limitless on-demand scalability, while you pay only for resources consumed. BY ROGER JENNINGS
11 First Looks
Product Listings ................................... .......................11 Review ...................................... ......................................1 ......................................13 3
39 Index of Advertisers 40 The Human Factor
S U H Y L Y D N A R Y B N O I T A R T S U L L I
“The primary economic justification justification for moving data center activity into the cloud is avoidance of capital expenditure for servers and associated networking hardware to handle peak instead of average loads.”
Where Did All the Developers Go? BY DANIEL APPLEMAN
32
Roger Jennings, “Retire Your Data Center,” p. 14
www.visualstudiomagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
3
Online
Check out these and other exclusive online articles and tutorials on the Visual Studio Magazine Web site at
VisualStudioMagazine.com
Content The blog will feature opinions and interviews with industry a developer you are constantly LEARN FROM THE As PROS facing the problem of how to keep up with all the new technologies being released while still getting your job done. You keep hearing about solutions to your programming problems but the question is: are they the right solutions for your particular needs? You could spend hours or even days trying to find the answers yourself, or you could let the experts do it for you. Redmond Media Group Events offers a variety of conferences and shows where you can learn about new technologies and what they might offer you, attend in-depth workshops that focus on topics specific to your needs, ask questions of the experts, and interact with your peers to discuss problems they face and what solutions they’ve come up with. Whether it’s Web design, .NET development, or SQL Server programming, we’ve got an event that matches your needs. Visit RedmondEvents.com RedmondEvents .com to learn more about upcoming conferences and shows.
ONLINE ARTICLES
Practical ASP.NET: Decoding Routes In his ongoing series on ASP.NET, Peter Vogel talks about the routing feature included in Service Pack 1 for .NET 3.5 and shows how to set up a site to use routes. In this installment, Vogel talks about the class file that you must create to handle the conversion between the meaningful URL provided by the user and the real path to your WebForm. LOCATOR+ CODE: VS0902PV1
Practical ASP.NET: Supporting Routing In this edition of Peter Vogel’s Practical ASP.NET column he goes beyond the basics of routing to look at some additional features. The goals here are to simplify your code and make life easier for your users. LOCATOR+ CODE: VS0902PV2
ONLINE BLOGS
VSM’s Big Issue Visual Studio Magazine ’s ’s Editor in Chief Patrick Meader and Managing Editor Guy Wright have started a collabor collaborative ative blog where they take a look at some of the bigger issues facing .NET developers these days.
insiders, and pose questions designed to stimulate discussion. Check out their blog at VisualStudioMagazine.com. VisualStudioMagazine.com. LOCATOR+ CODE: VS0901BI
ONLINE TUTORIALS
Classic VB Corner: Executing Debuggables Have you ever had one of those problems that only manifests itself in a compiled EXE, that you simply can’t reproduce in the Classic Visual Basic IDE? Or even worse, that only occurs on the client’s machines, and not on yours at all? Karl E. Peterson shares his debugging technique that works in both the IDE and EXE. LOCATOR+ CODE: VS0902KP1
Classic VB Corner: Got One Right! Conventional wisdom has it that version 1 of any Microsoft product or idea is really an alpha, that version 2 is the beta, and that the safe money rides on version 3. Then, following version 3, Microsoft generally proceeds to do its best to upset the success it found in that golden release. Karl E. Peterson takes a trip down memory lane to one of the most durable version 3 products ever to come out of Redmond. LOCATOR+ CODE: VS0902KP2
VirtualizationReview.com 1105 Media recently launched a new Web site devoted exclusively to covering all aspects of of IT virtuali virtualization. zation. Virtualization Review.com helps you harness the power power of virtuali virtualization zation by delivering news and in-depth coverage of the products, vendors, issues, and technologies t echnologies transforming transforming IT through virtualization. virtualiza tion. The site also features articles, tips, and timely information about all aspects of virtualization including servers, storage, desktops, applications, and more. Visit VirtualizationReview.com now to start your move to a more efficient, powerful virtual environment.
.NET NEWSLETTER SIGN-UP Every week, the .NET Insight e-mail newsletter brings you up-to-date news, technical information, opinions, interviews, and analysis on topics and technologies such as Visual Basic .NET, C#, SQL Server and data access, ASP.NET, wireless, Web services, and XML. Sign up for free at VisualStudioMagazine.com.
4
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
Your best source for software development tools! ®
LEADTOOLS Document Imaging v 16: by LEAD Technologies LEADTOOLS Document Imaging has every component you need to develop powerful image-enabled business applications including specialized bi-tonal image display and processing, document clean up, high-speed scanning, advanced compression (CCITT e w Ne N G3/G4, JBIG2, MRC, ABC) and more. n o n io rss i e r Ve V • Multi-threaded OCR/ICR/OMR/ 16 ! MICR/Barcodes (1D/2D) • Forms recognition/processing • PDF and PDF/A Paradise # L05 03201A01 • Annotation (Image Mark-up) • C/C++, .NET, WPF - Win32/64 $ 99 com/lead programmers.com/lead programmers.
2,007.
/n software Red Carpet Subscriptions by /n software /n software Red Carpet ™ Subscriptions give you everything in one package: communications components for every major Internet protocol, SSL and SSH security, S/MIME encryption, Digital Certificates, Credit Card Processing, ZIP compression, Instant Messaging, and even e-business (EDI)
Paradise # D77 09101L01
1,444.
$
99
transactions. .NET, Java, COM, C++, Delphi, everything is included, together with per developer licensing, free quarterly update CDs and free upgrades during the subscription subs cription term.
programmers.com/nsoftware
Acresso InstallShield 2009 Professional Windows by Acresso InstallShield Professional Edition is a powerful yet easy-to-use solution, ideal for both b oth novice and seasoned installation developers. While most homegrown installation tools are not optimized for current industry standards, InstallShield Professional makes your life easy by letting you take advantage of latest technologies—including technologies— including full support for Windows Vista.
Paradise # I21 02201A01
1,689.99
$
programmers.com/acresso
Infragistics NetAdvantage for .NET 2008 Volume 3
Paradise # I0M 02501F01 $
1,033.99
by Infragistics NetAdvantage® for .NET is our comprehensive suite of ASP.NET, Windows Forms, WPF and Silverlight line of business controls, components, and tools for the .NET platform. NetAdvantage for .NET has what you need to add no-touch AJAX to your Web site, awesome power and performance to your Windows Forms application, compelling user experiences leveraging Windows Presentation Foundation, and professionally polished user interfaces (UI). Includes Annual Subscription and Source Code
programmers.com/infragistics
800-445-7899 Prices subject to change. Not responsible for typographical errors.
VMware View Premier Starter Kit
dtSearch Engine for Win & .NET Add dtSearch‘s blazing speeds” (CRN Test Center) searching and N e ew w file format support 64-bi t t er r s si i o o n! • dozens of full-text and fielded V e data search options • file parsers/converters for hit-highlig hit-highlighted hted display of all popular file types 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
View Premier is an Enterprise-class Desktop and Application virtualization suite that enables you to take control of your desktops and applications while providing storage optimization. The Starter Kit is the entry level solution
Single Server Paradise # D29 02101A07
949.99
$
thatVMware includesInfrastructure 10 concurrent user licenses of Enterprise, vCenter Foundation, ThinApp, View Composer and View Manager. SnS is required and sold separately.
ea w s Re N le l e e w a s e e ! !
View Premier Paradise # V55 66101A01
VDI Included
CALL I
programmers.com/dtsearch
programmers.com/vmware
c-treeACE™ Professional
TX Text Control 14
by FairCom The c-treeACE database engine is a high performance database alternative proven by developers in mission critical enterprise systems, desktop deployments, and embedded devices for over 25 years. • Complete set of APIs including ADO.NET, LINQ, C#, C/C++, ODBC, JDBC, VCL, and dbExpress • Graphical productivity tools • Simple deployment • No DBA or ongoing administration Paradise # • Low deployment licensing costs F01 0131 • Cross-platform support for all major platforms including Windows, UNIX, Linux, and Mac OS X $ 99 Make your applications faster, easier to deploy, and more affordable with c-treeACE. programmers.com/faircom
N e e w w Word Processing Components Re l le e a s a s e e ! ! TX Text Control is royalty-free, robust and powerful word processing software in reusable component form.
Mindjet MindManager 8
Enterprise Architect 7.1
by Mindjet Do you harness the wealth of data, Web pages, and other input that comes your way every day? Is there a way to use it more effectively to formulate new ideas, sharpen your focus, and ultimately drive your success? New MindManager 8 for Windows is the answer.
Visualize, Document and N e e w w Control Your Software Project Re l le e a s a s e e ! ! by Sparx Systems Enterprise Architect is a comprehensive, integrated UML 2.1 modeling suite providing key benefits at each stage of system development. Enterprise Architect 7.1 supports UML, SysML, BPMN and other open standards to analyze, design, Corporate Edition test and construct reliable, well under1-4 Users stood systems. Additional plug-ins are Paradise # also available for Zachman Framework, SP6 0001 MODAF, DoDAF and TOGAF, and to integrate with Eclipse and Visual Studio $ 196.99 2005/2008. programmers.com/sparxsystems
711.
Unlike the usual linear-based approach of most productivity tools, MindManager 8 uses mind-mapping technology to let you capture, organize, andintuitive communicate information using an visual canvas. You’ll be able to work smarter and transform your ideas into action more quickly.
N e ew w Re l l e ea a s s e e ! !
for Windows 1 User Paradise # F15 17301A02
299.99
$
programmers.com/mindjet programmers. com/mindjet
• .NET WinForms control for VB.NET and C# • ActiveX for VB6, Delphi, VBScript/HTML, ASP • File formats DOCX, DOC, RTF, RTF, HTML, XML, TXT Professional Edition • PDF export without additional 3rd party tools or printer drivers • Nested tables, headers & footers, text frames, bullets, numbered lists, multiple undo/redo, sections, merge fields • Ready-to-use toolbars and dialog boxes
Multi-Edit 2008
by Telerik Add grid, combo, editing, navigation and charting functionality to your AJAX and ASP ASP.NET .NET projects. RadControls for ASP.NET enhances your Web applications by adding AJAX functionality to your ASP.NET ASP .NET projects. The suite takes full advantage of the features included in Visual Studio 2005. RadControls for ASP.NET helps developers deliver feature-rich, standards-compliant (WAI-A, WCAG 1.0, XHTML 1.1) and cross-browser compatible Single Developer Web applications, while significantly cutting Paradise # their development time. RadControls for ASP ASP.NET .NET TB3 01101A01 includes: RadEditor, RadTabstrip, RadInput, RadCalendar, RadUpload, RadWindow, RadAjax, $ 99
by Multi Edit Software Multi-Edit 2008 delivers, a powerful IDE, with its speed, depth, and support for over 50 languages. Enhanced search functions include Perl 5 Regular Expressions and definable filters. Supports large DOS/Windows, UNIX, binary and Mac files. File Sync Integration for: Delphi 6, 7, 2005, C++Builder 6, BDS 2006 and RadStudio 2007, VB 6, VC 6, VS 2003 & VS 2005. Includes file compare, code beautifying, command maps, and much more.
648.
$
919.99
Download a demo today.
programmers.com/theimagingsource
Telerik RadControls
RadGrid, RadMenu, RadChart,RadCombobox, RadTreeview and more. RadSpell, programmers.com/telerik
Paradise # T79 02101A01
N e ew w Re l l e ea a s s e e ! !
1-49 User Paradise # A30 01201A02 $
161.
99
programmers.com/multiedit
programmersparadise.com
Editor’s
Note
CALCULATING BY PATRICK PATRICK ME ADER
THE COST OF CHANGE
editor in chief
I hate doing something something twice, especi especially ally if I perceive perceive that redoing redoing something something is—or should be—unnecessary. be—unnecessary. Sometimes a portable USB storage device gives out or a file gets gets corrupted, corrupted,and and I find myself myself needi needing ng to reprodu reproduce ce content content or
6
redo an edit I’ve already done.It doesn’t happen often,but it happens,and pens, and I tend to react to such events in a consistent manner. manner. I curse fiercely. fiercely. I berate myself for not taking better precautions. Then I curse some more as I try to rescue the file. Will it open in notepad, perhaps? Will a different USB port be able to see the portable storage device? Experience tells me I’m better off knuck knuckling ling down and just getting to work,but I’m usually too worked up to to sit down and start anew immediately. immediately. I should take up yoga or meditation, learn a calming mantra. A better man might seek solace from his spouse, but I don’t want sympathy or empathy empathy at such times. No No,, I want to break stuff, to throw the offending computer computer out the window. I want to smash things. Given how much much I hate to redo stuff, I know one thing definitiv defin itively: ely: I’ I’d d hate hate to to be a developer. developer. Having to revisit and rewrite a half-dozen applications every time the company that makes my software tools changes something would leave me feeling feel ing queasy; havin havingg to retool everything I’ve ever done because of far-reach far-reaching ing changes would mean a weeks-,if not months-long stream stream of invecti invectives ves to make David David Mamet blush. I’d be in a semi-permanent semi-permanent rage state, tucked away away in a back office or closet so no one else would have to listen to me. It’ss one thing to redo something because I made an error; it’s It’ quite another to be forced to redo something because someone else makes a change that’s in my “best interests,” interests,” especially if that change alters how I must approach my job. job. But such changes happen all too often in software development. In her column last issue (Ask Kathleen, Kathleen, “Windo “Windows ws Workflow Changes Direction,” Direction,” January 2009), Kathleen Dollard tackled the extensive changes Microsoft is making in the next version version of Windows Workflow Foundation Foundation (WF). She
mizing the transition to the next version of WF WF.. In her opinion, devel developers opers will win over the long long run, but she also acknowledges that the price to achieve these gains is steep. This month’s Letters to the Editor include a response resp onse to Dollard’s article from Matt Fritz. Fritz laments the changes to WF,, as well as other, WF other, similar types of chang changes es that he’s he’s experienced as a Microsoft developer (see “Running the Development Treadmi readmill, ll,”” p. 8). Fritz notes that he’s he’s a strong believer in the Microsoft development platform, platform , but goes on to say that “using “using [developers] as beta and field testers ain’t right. It costs us and our companies time and money.” He’ss right. These changes He’ changes do carry a significant cost. cost. The flip side of his argument argument is this: this: Does Micros Microsoft oft save save Fritz money in the long run by by making these changes? changes? The answer is: It depends. depends. For some some developers, developers, the changes changes will pay for for themselves handily over over time; for others, others, the changes changes won’t won’t provide the same return, whether because the developer doesn’t need the changes, or because the changes mean abandoning a platform or technology they’ve invested considerable time and energy learning and deploying. One positive aspect of the changes to WF is that they’re occurring before before the product matured. Another positive positive aspect: WF is not a technology technology that’s that’s in widespread use, and the current implementation is lacking in significant sig nificant ways that the next version will address. There’ There’ss a reason more people don’t use it now. But what if you you’re ’re one of those who made an investment investment in the current version of WF? Microsoft is consciously throwing away the efforts efforts of the developers and companies companies it convinced to adopt this technology. technology. It’ It’ss penalizing its own best, most enthusiastic enthusiastic customers—the customers—the people, in fact, who had
noted how many changes planned plan forthat version 4 will break existing WF of 3.5the applications, andned urged you put off developing new WF-based applications if you haven’t haven’t begun creating them already. already. She also provided several tips for mini-
paid money for WF.When Microsoft’s Microsoft’ s approach to WF with a couple advisorsdiscussing to VSM , the conversation conversation would would usually start with “Big Bad Microsoft”for doing this to its customers but eventually would swing back to discussing why
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
S O I D U T S N O S N H O J T A P Y B O T O H P
Integrate Mapping and GIS into Your Applications Give your users an effective way to t o visualize and analyze their data so s o they can make more informed decisions and solve business problems. By subscribing to the ESRI ® Developer Network (EDNSM), you have access to the complete ESRI geographic information system (GIS) software suite for developing and testing applications on every platform. Whether you’re a desktop, mobile, server, or Web developer, EDN provides the tools you need to quickly and cost-effectively integrate mapping and GIS into your applications.
Subscribe to EDN and leverage the power of GIS to get more from your data. Visit www.esri.com/edn www.esri.com/edn.. Copyright © 2009 ESRI. All rights reserved. The ESRI globe logo, ESRI, EDN, and www.esri.co www.esri.com m are trademarks, registered trademarks, or service marks of ESRI in the United States, the European Community, Community, or certain other jurisdictions. Other companies and products mentioned herein may be trademarks or registered trademarks of their respective trademark owners.
EDITOR’S NOTE
>> COST OF CHANGE
The product hadn’t achieved maturity, 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.
8
someone would put an immature or little-used technology to work in a mission-critical scenario. On the surface, surface, this argument argument strikes me as bizarre. bizarre. Are the companies Microsoft convinces to use its technologies culpable when Microsoft changes cha nges things up? You expect some risk r isk when you use a beta or community technology preview technology.. Maybe the same holds true for a version 1 product.We nology all know the adage that you shouldn’t adopt a pre-version 3 product from Microsoft, Microsoft, but we don’t actually mean it, do we? we? Regardless,that argument shouldn’t be in play here: Microsoft is scrapping a version version 3.5 product. product. The product product hadn’t hadn’t achieved maturity, maturity, nor had it achieved widespread acceptance, but it seems unlikely you could see this coming if you were a company that relied reli ed on WF. The changes that are occurring occur ring in WF wouldn’t seem so significant significa nt if there weren’t weren’t other examples of develop developers ers having to rework their applications because Microsoft made changes of a similar scope in other technologies. technologies. For example, the introduction introduction of a .NET version of VB roiled the VB community for years,and we’re still feeling the the aftershocks of some of those design decisions. decisions. Micro Microsoft soft was careful to note when it introduced introduced a .NET version of VB that the existing code code developers had written would still work. Similarly Similarly,, WF 3.5 apps will continue to to function. But the blunt truth is: Discontinuing a language or technology is a death sentence to future development for that language or technology,and technology, and even existing applications face hardware and other limits on their longevity.. Sooner or later, longevity later, developers will have have to move on, whether they want to or because they have have to. Eve Even n if existing apps continue to function or are maintained indefinitely, indefinitely, your ability to earn a living with that tool or technolog y is severely limited, and you incur an opportunity cost when you need to abandon what you’re doing now for something else. I’m ambivalent about what constitutes the proper balance between maintaining backward compatibility and introducing new features. I want the software I use to provide features that help me do my job better and save me time over the long run. It should also be noted that there’s the re’s a cost to backward compatibility,, especially in terms bility terms of application performance.As performance.As much as I hate to redo things or have to rework things to achieve
But the central central issue is this: My notion of compellin compellingg doesn’t doesn ’t always match match that of the software’s software’s designers. What strikes a software developer as essential can strike me as capricious (Microsoft (Microsoft Office’s Office’s ribbon, anyon anyone?). e?). It might be that a company could could change its product so it serves 95 percent of its users better, better, but alienates me in the process. process. I just don’t don’t care how much the first group wins if the software becomes unusable for me. That’ That’ss part of the equation that a company company that that creates software must consider. consider. When a company bets I’ll like a feature enough to not mind that it no longer works as it used to,that company places bets with my money, money, as well as its own. And I’d like a company that places bets with my money to do so at least as conservatively conservatively as I would. In the case case of WF WF,, Microsoft isn’t isn’t just betting with other people’ people’ss money; it’s saying the chips those early adopters bought from Microsoft can never be redeemed. A company ought to be extremely careful about making such bets, because they represent a major withdrawal from the goodwill bank of their customers. Doing this even once can be enough to turn a customer against you, so a change that affects only one person in 20 can still have significant consequences. consequences. If a company does this routinely, routinely, it’s only a matter of time until it affects all its customers. customers. What concerns me most about what occurred with WF are the implications these changes portend for the future for those who use Microsoft technologies. Today WF is a peripheral technology.There are people to whom it’s important,but important, but there are other technologies such as Office, Windows, or even VB that are not so peripheral. For example, Windows ComCommunication Foundation is undergoing its own changes that I understand will have an—admittedly less dramatic—effect on backward compatibility. compatibility. And Microsoft has announced that LINQ to SQL is basically shifting to something akin to maintenance mode, which is worrisome for many developers who see it as their only workable data solution at the moment. Sure, I expect something something else, as yet unannounced, unannounced, to take its place (Entity Framework?). Framework?). But how many many times will you as a developer have to go through this thi s process? More to the point, how long will you suffer Microsoft to put you through this? VSM
functional I’m willing tofor accept changes that break how thingsequivalence, work now in exchange a significant improvement in how things will work going forward—especially forward—especially when the reason for the change is compelling.
Talk Back: How docompatibility you go aboutand striking the proper balance between backward introducing new features in your own software? soft ware? Tell Tell me at
[email protected] or
[email protected].
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
Get tips. Get code. Get the best best how-to articles on the net.
ONLINE
www.visualstudiomagazine.com
Letters Letters to Visual Studio Magazine are welcome. Letters must includ include e your name, address, and daytime phone number to be considered for publica- tion. Letters might be edited for form, fit,, and sty fit style. le. Le Lette tters rs expr express ess the vie views ws of the individual authors, and do not necessarily reflect the views of the editors, VSM VSM,, or 1105 Media. Please send them to Letters to the Editor, c/o Visual Studio Magazine, Magazine, 230 California St., San Francisco, CA 94111; fax them to 415-814-0961; or e-mail them to
[email protected].
Running the Development Treadmill athleen Dollard’s Dollard’s article on the changes in the upcoming version of Workflow [Ask Kathleen,“Windows Kathleen, “Windows Workflow Changes Direction,” Direction,” January 2009] reminded me that the same thing happened with SQL Server DTS 2000/2005, as well as with the MapPoint MapPoint object model and ADO. Now SQL Notification Notification Services was dropped in 2008? Are you kidding? It makes you wonder: How many times do you have to to relearn things you used to know how to do? I’m a strong believer in the Microsoft Microsoft developer platform, and I believe the tools do get better over time. But using us as beta and field testers ain’t ain’t right. It costs us and our companies time and money. money. Now I have have Biztalk, Biztalk, Win Windows dows Communica Communication tion Foundation, Foundation, Win Windows dows Workfl orkflow ow,, and LINQ LINQ on the the “wai “wait-and t-and-see -see”” list, with more more to come come,, no doubt. doubt. If Micr Microsoft osoft still believes believes that developers are are the foundation foundation of its business, it needs to reconsider reconsider this strategy.. Gate strategy Gatess himself talks about about the great companie companiess of yest yesteryea eryearr that couldn’ couldn’tt see when they started doing doing things wrong, wrong, like DEC, Wang, and Novell Novell (and now now General Motors?). It’ It’ss a mistake to alienate the developer community. community. Every company has—or will have—a Toyota Toyota in the rearview mirror. Hey Bill! Come back for awhile; awhile; we need you to clean house! house! Matt Fritz, originally posted posted online
K
VisualStudioMagazine.com February 2009 • Volume 19 • No. 2 Editorial Staff Vice President, Doug Barney Editorial Director Editor in Chief Patrick Meader Managing Editor Managing Editor, RMG Associate Managing Editor, RMG
Bill Wagner’s article covering what VB developers should know about C# would have been more useful useful if if he had ancho anchored red the gee-w gee-whiz hiz discussi discussion on of itera iterators, tors, lambda lambdas, s, and closures closures with at least a mention of the closest approximation approximation in VB.NET functionality, functionality, so that we could have gotten a clue as to what the differences are and why we should care [C# Corner, Corner, “What VB Devs Should Know About About C#,” C#,” December 2008]. As it is, this read more like a “things I like to do in C#” article than an aid for folks trying to bridge the gap between VB.NET and C#. Bill Clardy Clardy,, Ora Orange, nge, Cali Calif., f., origina originally lly posted online online
Wendy Gonchar Katrina Carrasco
Contributing Editors Andrew J. Brust, Ken Cox, John Cronan, Dan Fergus, John Gavilan, Roger Jennings, Don Kiely, Mar tin Kulov, Jeff Levinson, Bill McCarthy, John Charles Charles Olamendy amendy Turruel Turruellas, las, Keith Keith Pleas, Pleas, Peter Peter Varhol, Varhol, Bill Bill Wagner Wagner
Art Staff Creative Director Scott Shultz Graphic Designer Erin Horlacher
Online/Digital Media Editor, VisualStudio Becky Nagel Magazine.com Executive Editor, New Media Michael Domingo Online News Editor Associate Editor, Web Web Producer
Kurt Mackie Gladys Rama Shane Lee
Director, Web Development
Rita Zurcher
President
Henry Allain
Vice President, Publishing Director of Marketing Online Marketing Director Marketing Programs Manager
President & Chief Executive Officer Senior Vice President & Chief Financial Officer Executive Vice President
Matt N. Morollo Michele Imgrund Tracy S. Cook Videssa Djucich
Neal Vitale Richard Vitale Michael J. Valenti
President, 1105 Events
Dick Blouin
Vice President, Finance & Administration
Christopher M. Coates
Vice President, Audience
Examples Would Be Nice
Guy Wright
Marketing & Web Operations Vice President, Information Technology & Web Operations Vice President, Circulation
Abraham M. Langer Erik A. Lindgren Carmel McDonagh
Jeffrey ey S. Klein Klein Chairman of the Board Jeffr
REACHING THE EDITORS Editors can be reached via e-mail, fax, telephone, or mail. A list of editors and contact information is available at VisualStudioMagazine.com. E-mail: E-mail is routed is routed to individuals’ desktops. Please use the following form: FirstnameinitialLas FirstnameinitialLastname@1105media
[email protected]. .com. Do not include a middle name or middle initials. Telephone: The switchboard is open weekdays 8:30 a.m. to 5:30 p.m. Pacific time. After 5:30 p.m. you will be directed to individual extensions.
Correction:
The recent First Looks review of Compuware Compuware’s ’s DevPartner DevPartner Studio contained an error when discussing the capabilities of that tool’s Performance Performance Analyzer [“Understand [“Understand What Your Your App Does, Does,” ” January 2009]. A nalyzer canYou be configured analyze ASP.NET ASP .NETofapplications running runnin g on both localPerformance local and remote and remote Analyzer compu computers. ters. can read read antoupdated version the review online at VisualStudioMagazine.com that explains the general steps you need to take to use Performance Analyzer with ASP.NET. Locator+ code: VS0901FL VSM regrets VSM regrets the error. 10
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
415-814-0950; 0; Fax 415-814-0961 San Francisco Office 415-814-095 949-265-1520; 20; Fax 949-265-152 949-265-1528 8 Irvine Office 949-265-15
Corporate Office 818-734-152 818-734-1520; 0; Fax 818-734-152 818-734-1528 8 Visual Studio Magazine The opinions expressed within the articles and other contents herein do not necessarily express those of the publisher.
First PRODUCT LISTINGS
+
Looks
REVIEWS
DataDirect Connect Connec t for ADO.NET, List & Label 14, and MobileForms Mobi leForms Toolkit Toolkit 2009 2 009 DataDirect Connect for ADO.NET
D
DataDirect Technologies has released DataDirect Connect for ADO.NET data providers. With DataDirect Connect for ADO.NET, developers can write and deploy .NET enterprise applications that connect to multiple databases including Oracle, DB2, Microsoft SQL Server, and Sybase. The latest product release includes new provider features for each major database, new performance-tuning options, and introduces DataDirect Bulk Load, a standards-base standards-based d implementation implementa tion of bulk-load functionality that provides a method for moving volume-intense data across Oracle, DB2, Microsoft SQL Server, and Sybase databases, without having to deploy and load client libraries. The suite of ADO.NET data providers uses a 100 percent managed code architecture, therefore DataDirect Connect for ADO.NET eliminates the need for database client libraries. Because managed code runs in the Common Language Runtime (CLR) environment it reduces risks and closes holes that unmanaged code leaves exposed, providing developers with versatile deployment options available in both application and client-server environments. With DataDirect Connect for ADO.NET developers get full support for .NET Framework Framework.. The latest release of DataDirect Connect for ADO.NET additionally offers performance enhancements including additional tuning options that support a variety of application performance scenarios and statemen statementtcaching, a option that requires no the changes toconnection the application and can increase efficiency of applications connecting to Oracle, DB2, and Sybase.
DataDirect Connect for ADO.NET now supports Oracle 11g R2, SQL Server 2008, and DB2 iSeries V6R1. A complete list of database provider features is available online. DataDirect Connect for ADO.NET
DataDirect Technologies Price: Contact vendor for pricing Web: www.datadirect.com Phone: U.S.: 800-876-3101;
World: 44 (0) 1753 218 930
List & Label 14 Combit has released version 14 of its reportgenerating software List & Label. Among the new features is the inclusion of a real-data-preview, so changes can now be seen with real data, without having to leave the Designer. Within the preview there’s also an integrated index to ease navigation through the report. Additionally, it’s now possible to mix different formats within the same document. Now multiple formats are possible as well as the choice of printer type. Using a single record from the database, the user can define real rows that can be represented in a line diagram with respect to time. Also new for Professional and Enterprise Edition 14 is the generation of DOM code. DOM code is now automatically provided by the List & Label object model directly from the project file. The DOM viewer has been completely reworked, rework ed, and now includes a search utility ut ility for
objects and properties. Besides functions and objects, the user can now create their own designer actions with DOM and Designer. New with version 14 is support for Delphi 2009. Additionally, the project parameter interface has been extended with a method and allows the storage of SQL queries or even complete data sets within a project. Other additions in version 14 include an extended formula assistant, assista nt, better overview of property values, magnetized help lines in the Designer,, and your own Designer actions. Designer With List & Label Lab el software, developers can equip their own applications with functions to assist in the generation of reports, statistics,
forms, lists, and labels. Only a few lines of code are required to integrate the report generator into existing applications. The Designer, which can be passed on to end users without having to pay additional license fees,tool is availabl available e in 15 languages. The development for reporting functions as well as Web reporting is available in German or English and can process almost all
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
11
Instantly Search Terabytes of Text of indexed, unindexed, fielded data and full-text search options (including Unicode support
PRODUC T
LI STI NGS
+
RE V I E W S
dozens
character sets. All three th ree editions of List & Label can be integrated into a large variety of programming languages. List & Label 14
for hundreds of international languages) parsers / converters for hit-highlighted display of all popular file types
Combit GmbH Price: Standard Edition is available for 370 euro; Subscription Editions Profes-
sional starts at 1,380 euro; and Enterprise at 2,094 2 ,094 euro. Web: www.combit.net/en Web:
file
Spider supports
static and dynamic web data; highlights hits while displaying links, formatting and images intact
Phone: +49 (0) 7531 90 60 10
MobileForms Toolkit 2009
w ith Spiderr esktop w D h Spider Network w it Dss VD DV D D / CD orr ffo h h s s i i l l b b u u P P
Spider W eb w ith N New N ET . & n i W r -bit 64 Engine fo r L inux Engine fo
API supports .NET, C++, Java, databases, etc.
New .NET Spider API
The Smart Choice for Text Retrieval® since 1991
“Bottom line: dtSearch manages a terabyte of text in a single index and returns results in less than a second” – second” – InfoWorld
“For combing through large amounts of data,” data,” dtSearch “leads the market” – market” – Network Computing
dtSearch “covers all data sources ... powerful Web-based engines” – engines” – eWEEK
dtSearch “searches at blazing speeds” – speeds” – Computer Reseller News Test Center
See www.dtsearch.com for hundreds more reviews, and hundreds of developer case studies
Resco has released an updated suite of controls and libraries for .NET Compact Framework (CF) developers targeting Pocket PCs, smartphones, and Windows CE .NET devices. The new suite, MobileForms Toolkit 2009, is optimized for Microsoft Visual Studio 2008 and Microsoft .NET CF 3.5. Major enhancements to the suite include adding Touch functionality to all controls and a new graphical user interface. Adding Touch functionality to mobile applications is a simple matter of setting up a single property propert y in Microsoft Visual Studio. MobileForms Toolkit 2009 includes many controls and libraries that tackle most of the common problems that developers encounter developing for the mobile mo bile environment. Tools Tools include SmartGrid—a grid control with built-in auto edit capabilities, Touch scroll support, and the ability to save different SmartGrid layouts to XML files; AdvancedList— a professional list control suitable for small displays of mobile devices and includes DelayLoad functionality that loads only visible data for fast previews while additional data is loaded on demand; CompactChart—a charting control with five chart types including Pie, Bar, Line, Doughnut, and Area charts; OutlookWeekCalendar and OutlookMonthCalendar—day/week and month/year appointment scheduling controls; OutlookDateTimePicker—a OutlookDateTimePicker—a modern version of a common control providing advanced styles; DetailView—for creating mobile user input forms where input controls are collected in a compact environment giving the form standard Windows Mobile look and feel; InkBox— an ink control suitable for quick notes or signatures; ImageBox—an image control supporting various graphic formats; CustomKe CustomKeyboard—a yboard—a flexible control supporting custom keyboard layouts; OutlookShortcutBar—a popular shortcut control common for all modern moder n applications; a library for playing and recording audio; and more. For more information about the Resco MobileForms Toolkit 2009 and a complete list of controls and libraries, l ibraries, visit visit http://tinyurl.com/9wukrz. MobileForms Toolkit 2009
Resco Price: Standard Edition $499.95, Professional Edition $999.95,
Enterprise Edition $1,999.95 Web: www.resco.net Fax: +421 2 090 2010
Contact dtSearch for fully-functional evaluations
s end product prod uct information infor mation to New Products Products Editor, Editor, c/o Editor’s Note: Please send
VisualStudioMagazine, 230 California St., San Francisco, Francisco, CA 94111; Phone: 415-814-0950, fax: 415-814-0961; e-mail
[email protected].
1-800-IT-FINDS 1-800-IT -FINDS • www www.dtsearch.com .dtsearch.com
PRODUCT LISTINGS
+
REVIEWS
Develop Help Develop Help Content Lik Like e a Professional MadCap Flare 4.1 is a professional development environment for creating documentation for a wide range of formats based on a single-source (XML). As a programming writer, I was struck by how Flare offers so many must-have features of Visual Studio to technical writers. Information developers have have much in common with software developers. They want to work in a familiar, integrated environment that organizes files, flags errors, assists with testing and reporting, controls the build process, and generally generall y makes them more efficient. Flare does all this and more. mo re. For example, it takes a cue from software development by allowing projects projec ts to link to common content. As with pre-built software components, you can store and update shared pages—for example, legal disclaimers—in one place. All of the projects and documentation suites can incorporate the latest version into the build automatically. IntelliSense, an essential feature for writing code, is REDUCE KEYSTROKES KEYSTROKES AND WRITER’S CRAMP You can store now available in documentation projects. As you write frequently used resources as snippets in MadCap Flare 4.1. Just instructions, the IDE suggests phrases that appear in drag-and-drop the content into the editor. For larger files, you can the project’s topics. Likewise, you can drag snippets link to complete boilerplate topics from a central location. and drop them directly into a topic. To accommodate Windows Presentation Foundation (WPF) Help 2). Another valuable output would be XAML markup for and Silverlight software projects, Flare now supports an array of Silverlight apps. vector graphic types, including the XAML format. A nice touch is Source control is essential for programmers and writers writer s alike. the ability to convert those images automatically to Web-safe When you create a Flare project, there’s the re’s a checkbox to bind to a formats such as .GIF or .JPG for browser-hosted output. Speaking source control provider, including Visual SourceSafe, Team of formats, Madcap creates .PDF and .XPS files directly, without Foundation Server, and a generic plug-in. The Bind Project requiring Microsoft Word, Adobe FrameMaker, or Adobe Acrobat option recognized and connected to my SourceGear Vault as intermediaries. Unfortunately, MadCap still doesn’t generate provider—a real bonus. That said, the IDE crashed when I tried to files that integrate with Visual Studio’s help collections (MS cancel out of a Vault connection using the th e Advanced option. You’ll appreciate the small conditional-text touches like automatically adjusting cross-references for the medium. For AT A GLANCE example, in a PDF you might generate “as shown on p. 32” where the HTML version, which doesn’t use page numbers, MadCap Flare 4.1 would substitute a hyperlink. MadCap Software Web: www.madcapsoftware.com Web: MadCap’s user assistance is polished polishe d and plentiful. The GetPhone: 858-320-0387 ting Started Wizard, sample projects, videos, dynamic help, and Price: $899 help topics get you up to speed and over the hurdles. Quick Facts: Integrated development environment On the downside, Flare sets off your firewall alarm as it for authoring user manuals, online help, and Web accesses the network to validate your license key usage, and pages. Generates multiple output formats from a single XML source. the software stops working until you—or the IT department— Pros: File linking and conditional text; XML editor; unblock its stealth access. With product announcements that IntelliSense support; drag-and-drop snippets; sourcestart with “Dear Propeller Heads!” the folks at MadCap seem control friendly; command-line mode; built-in .PDF friendly, fun, and upfront. That’s why a high-handed licensing and .XPS generators; valuable user assistance. Cons: Doesn’t generate integrated help for Visual VSM approach is disappointing and out of character. Studio help collections; sets off firewall alarm to validate license key. Ken Cox is a Canadian .NET programming writer and the t he author of
M
“ASP.NET “ASP .NET 3.5 for Dummies” (For Dummies, 2008).
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
13
FEATURE
R E T I R E Y O U R D A TA TA C E N T E R
Retire You ourr Data Center Visual Studio 2008, ASP ASP.NET, .NET, and the Azure Services Serv ices Platform combine to simplify local development developme nt of data-intensive Web apps and automate their deployment in Microsoft data centers. The result: You get maximized availability and reliability with wi th almost limitless on-demand scalability, scalab ility, while you pay only for resources consumed. BY ROGER JENNINGS
TECHNOLOGY TOOLBOX VB.NET C# SQL Server ASP.NET XML XM L Other: Azure Services Platform Elastic(EC2) Compute Cloud
14
he three-year hiatus between the Microsoft Professional Developers Conference (PDC) 2008 and its 2005 predecessor gave Ray Ray Ozzie and his newly expanded development developm ent team the opportunity oppor tunity to play catch-up with Amazon.com Amazon.com Inc., Google Inc., and other major players in the race to capture developer mindshare for
T
cloud computing. Microsoft’ Microsoft’ss cloud candidate— Windowss Azure—occupied Window Azure—occupied the bulk of Ozzie’ Ozzie’ss Day One PDC keynote keynote and was the subject of of 39 sessions, more than twice as many many as the nextmost-discussed topic—Visual Studio. Windo Windows ws Azure is an Internet-facing operating system that promises to enable .NET developers to leverage their current ASP.NET ASP.NET,, WindowsCommunication Foundation (WCF), and Windows Workflow Workflow programmingg skills to deploy .NET Web grammin Web applications to Microsoft’s newly built data centers quickly and easily.. Microsoft easily Microsoft’s ’s message to VS developers is to “use your your existing tools,knowledge, and skill set” for projects you deploy to Windows Azure.
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
The Azure Services Platform,for which the Windows Azure OS serves as the foundation, provides “massively “massively scalable”table and blob storage services,a persist persistent ent message-queue message-queue service, several .NET utility services (formerly code-named “Zurich”),a Live operating environment, environment, and the successor to SQL Server Data Ser vices that’s now called SQL Data Services (see Figure Figure 1, opposite page). I’ll give give you you a brief intr introduct oduction ion to the platform’s objectives and its architectural details to achieve them, and describe how Azure differs from its cloudcloud-based based competitors. competitors. Then I’ll drill down into programming data-intensive Web application applic ationss that take advantage advantage of Azur Azure’ e’ss
S U H Y L Y D N A R Y B N O I T A R T S U L L I
R E T I R E Y O U R D A TA TA C E N T E R
The primary economic justification for moving data center activity into the cloud is avoidance of as sociated networking capital expenditure for servers and associated in stead of average average loads. hardware to handle peak instead unique development and deployment tools. Finally, I’ll discuss an instrumented ASP.NET ASP.NET test harness for Azure Table Services that you can download,run download, run locally with the community technology technology preview (CTP) of the Windows Windows Azure SDK,and SDK, and then deploy to the Windows Windows Azure CTP running in a Microsoft data center (see the Go Online information on p. 25 for details). Future VSM issues will cover Blob Services,Queue Services,SQL Services, SQL Data Services, Services,and and .NET Services. Services. “Cloud computing” is a catch-all term for Webbased utility computing operations provisioned as pay-by-usage software services and accessed over the Internet. Interne t. Amazon Web Services and Google App Engine are probably the best-known cloud-computing services, servic es, but Web-ho Web-hosting sting firms, firms, such as Racksp Rackspace ace Hosting Inc., Inc., and specialty vertical-market vertical-market providers providers like SalesForce.com SalesForce.com Inc., also fit into the cloud-computing picture. picture. The primary economic economic justification for moving data center activity activ ity to the cloud is avoidance of capital expenditure for servers and associated networking hardware hardware to handle peak peak instead of average loads. Other benefits benefits include reduction of IT management and operating costs, improved application reliareliability and availability, availability, and the ability to scale Web Web applications up-and-out quickly to match rapid increases increas es in traffic. When the traffic traffic subsides, such as after holiday holiday sales, resourc resources es can return to the pool automatically automati cally or by manual intervent intervention. ion. Cloud deployment also offers a rapid method for proving Web application or service concepts without making infrastructure investments. Azure Echoes AWS Azure’s architecture most closely resembles a combination of Amazon Web Web Services (AWS) Elastic Compute Cloud (EC2) running Windows Server 2003 R2 with SimpleDB SimpleDB for for semi-structured semi-structured tables, Simple Storage Service (S3) (S3) for blob storage, storage, Simple Queue Service (SQS) for messaging between applications, and Elastic Block Store to persist other instance data (see Table 1, p. 23, and Addi Additiona tionall Resour Resources, ces, p. 25). Amazon EC2 running Windows Server and Simpl eDB are in the beta-testing stage, as is the Google Google App Engine (GAE). Microsoft won’ won’tt reveal pricing for Azure services until later in 2009 when version 1 is
closer to release. Howev However er,, the current word is that Azure will be “competitive, “competit ive,”” presumably with the AWS, GAE, or both both price lists, and the Service Level Agreement Agreement will be factored into into monthly charges. It’ It’ss not known whether Microsoft will adopt Google’ss approach of billing only for App Engine usage in excess Google’ excess of fix fixed ed quotas for free free CPU time, time, netw network ork ingress ingress and egress, egress, and storage.
FIGURE 1 Move ASP.NET Web Apps to the Cloud The foundation for the Azure Services Platform is the Windows Azure operating system, which provides the fabric for virtualized Windows 2008 Server instances; schemaless persistent table, blob, and queue storage; .NET Services for managing authentication/ authorization, interservice communication, communication, and workflows; and SQL Services for data management with relational database features and consumer-oriented Live services. Like the Google App Engine, Azure provides a development environment that emulates its cloud operating system and storage services.
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
15
TA C E N T E R R E T I R E Y O U R D A TA
Windows Azure runs on Windows Windows Server 2008 with virtualization provided by Microsoft’s Hyper-V hypervisor technology to deliver a runtime runtime fabric that handles load balancing, balancing, data replication, and resource management.According to Microsoft’s Microsoft’s Erick Smith, the Azure Fabric Fabric Controller maintains maintains a graph of the inventory inventory of physical and and virtual machines, machines, load balancers, balancers, routers, and switches it manages in a Microsoft data center. center. Edges of the graph are are interconnect interconnections ions of various types,for example, network, netw ork, serial serial,, and power power cables. cables. You specify specify the topology topology of of your ser vice vice—the —the number num ber and conn ecti ectivit vityy of role roles, s, the att rib rib-utes and locations locations of the various hardware hardware components, components, as well as the numbers numbers of fault fault/upd /update ate domains domains and maximu maximum m instances of each role you need with a declarative Service Model. Model. In this respect, Windows Azure Azure management features are similar to those offered by RightScale for AWS and employed by the GAE. Roles are runnable runnable compon components ents of an applicat application; ion; role instances run on the fabric’s nodes nodes and and channels channels connect connect roles.
The CTP limits applications to managed code authored in VS 2008 that runs under a custom custom version version of medium trust Code Code Access Acc ess Security. Microsoft promises promises future support for Python, Ruby,, native code, Ruby code, and Eclipse. Eclipse. Fault domains for domains for role instances represent a single single point of failure, such as a rack; rack;update update domains for performing rolling software upgrades or patches run r un across multiple fault domains (see Figure 2).Ultimately,you’ll 2).Ult imately,you’ll be able to specify your Service Model with Oslo’s Oslo’s domain-specific language tools and store the model in the Oslo Osl o repository. The current CTP released at PDC 2008 doesn’t expose the Service Model; instead the Windows Azure Azure Tools Tools for Microsoft Visual Studio add-in defines common Azure application-role templates for Web Web Role, Worker Role, and Workflow Workflow.. The Web Web Role enables creating a new Web Cloud Service or Web and Worker Cloud Se rvice as an ASP.NET ASP.NET Web Web applicati on running on IIS 7 instance(s) under Windows Windows Server 2008 (see Figure 3, opposite page). Windows Azure doesn’t doesn’t support fil e-system Web Web site projects. Worker Roles are asynchronous operations that perform background processing processing when added to Web Web projects; roles also can create standalone Worker Worker Cloud Services. The most common use for Worker Roles is processing messages added to an Azure Queue. Queue. Workflows enable enable writing standalone CloudSequentialWorkflow projects or can be incorpo rated in Web or Worker Worker Cloud Se rvices. Azure’s October 2008 CTP limits testers to a maximum of 2,000 runtime hours with up to eight instances of a single production production application havhaving one Web Web and, optionally,one Worker Role.
FIGURE 2 Distribute Instances Instan ces Across Azure Domains The Azure Fabric Controller automates deploying computing and network resources to support application instances on multiple f ault domains (server racks) to prevent a single point of failure. Instances run on nodes, which usually are virtualized Windows 2008 Servers but can be physical machines; Azure currently maintains a master and two replicas of application roles. XCopy application deployment simplifies adding new or upgrading app lications. Rolling upgrades or service releases only affect a single update domain at a time to prevent application downtime. Unlike Amazon and Google services, Azure offers an intermediate Staging deployment for new apps that developers can test with a private URL, then deploy to the account’s public Production URL (see Figure 6, p. 22).
16
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
Emulate the Cloud Locally Azure was in a limited (private) beta stage at press time.You can apply for admission to the Azure Services Platform beta program at the Microsoft Connect site; the OakLeaf OakLeaf blog offers offers a walkthrough walkthrough of the somewhat convoluted sign-up process (see Additional Addition al Resourc Resources, es, p. 25). Howev However, er, you don don’t ’t need to wait for a beta invitation because downloading and installing the Windows Azure SDK (October 2008 CTP) and Windows Azure Tools for Microsoft Visual Visual Studio (October 2008 CTP) lets you emulate emul ate the t he Azure Ser Service vice s Plat for form m on your local development development machine. machine. Installing the the SDK adds a start menu folder with Development Fabric and Development Storage Storage nodes, as well as Release Notes, Windo Windows ws Azure SDK Command Prompt, and Windows Azure SDK Documentation nodes. Choosing the Development Fabric and Development Storage nodes or clicking their icons in the Taskbar’s Notification Area opens management dialogs for the two service emulators (see Figure 4, p.18). When Wh en you specify one one of the Cloud Services templates (typically a Web Cloud Service) for a
R E T I R E Y O U R D A TA TA C E N T E R
Downloading and installing the Windows Azure SDK (October 2008 CTP) and Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP) lets you emulate the Azuremachine Services your local development . Platform on new VS 2008 project, the add-in generates generates a solution with a Cloud Clou d Servic Servicee proj project, ect, whic which h con contains tains Servic ServiceCon eCon-figuration.cscfg figuration.csc fg and ServiceDef ServiceDefiniti inition.c on.csdef sdef file files, s, as well as an ASP.NET ASP .NET Web Web Role application. applicat ion. You also must expand the t he Windows Azure SDK’s \Program Files\Windows Azure SDK\v1.0\samples.zip file to a temporary folder. folder. Then add the \Temp\Storage\Temp\StorageClient\ Lib\StorageClient.csproj and \Temp\HelloFabric\Common\Common.csproj projects to your solution by right-clicking on the solution in Solution Explorer and selecting Add an Existing Project. Add the two project files as references references to your ProjectName _WebR _ WebRole ole applic application ation.. The StorageClient library delivers wrapper classes for REST API operations operations on Azure Blob, Queue, and Table Services; the Common Common library provides provides ApplicationEnvironment classes for logging and other local fabric-related fabric-related activities. activities. The Azure Tools add a reference to Microsoft.Ser viceHosting.Serv iceRuntime.dll for the local fabric automatically. Right-click on the Cloud Service project node and choose choos e Create Test Test Storage Storag e Tables Tables to add ProjectName tables to your local instance of SQL Server 2005+ Express. At this point, you can import page and class fil es for existing ASP.NET ASP.NET projects or create a new Web application from scratch. Settings in the ServiceConfigurati ServiceConfiguration.cscfg on.cscfg file determine whether your application uses local or cloud storage when emulating the hosted service. Here’ss a ServiceConfiguration.csfg file with entries Here’ for both local and cloud storage with AccountSharedKey values abbreviated: <?xml version="1. version="1.0"?> 0"?> <ServiceConfiguration serviceName="SampleWebCloudService" xmlns="http://schemas.microsoft.com/ xmlns=" http://schemas.microsoft.com/ ServiceHosting/2008/10/ ServiceConfiguration"> <Role name="WebRo name="WebRole"> le"> <Instances count="3"/> <ConfigurationSettings> <Setting name="AccountName" value="devstoreaccount1"/>
value="Eby8vd … MGw=="/> <Setting name="BlobStorageEndpoint" value="http://127.0.0.1:10000/"/> value=" http://127.0.0.1:10000/"/> <Setting name="QueueStorageEndpoint" value="http://127.0.0.1:100001/"/> value=" http://127.0.0.1:100001/"/> <Setting name="TableStorageEndpoint" value="http://127.0.0.1:10002/"/> value=" http://127.0.0.1:10002/"/> <!-- <Setting name="Account name="AccountName" Name" value="<youraccountname>"/>
FIGURE 3 Choose a Pre-configured Cloud Service, Role or Workflow The October 2008 community communit y technology preview ’s Windows Azure Tools Tools for Visual Studio 2008 add-in provides pre-configured Web Cloud Service, Worker Cloud Service, Web and Worker Cloud Service, Web Role, Worker Role, and CloudWorkflow templates for Windows Azure Web applications and services. Creating a new Web Cloud Service adds a ProjectName service service node with ServiceConfiguration.cscfg and ServiceDefinition.csdef files, and a pointer to a ProjectName _WebRole project, proje ct, as shown for this artic le’s SampleWebCl Sampl eWebCloudSe oudService rvice project in Solution Explorer. Common and StorageClient class libraries provide local logging features and wrapper classes for Azure Storage Services’ REST API. The Limog class contains code to regenerate the CustomerT CustomerTable. able.
<Setting name="AccountSharedKey"
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
17
TA C E N T E R R E T I R E Y O U R D A TA
Azure tables have a distributed architecture that’s related to Google’s Google’ s Bigtable Bigtab le, and Microsoft says Azure tables are designed to scale to billions of entities and terabytes of data. <Setting name="AccountSharedKey" value="<YourPrimaryAccessKey>" /> <Setting name="BlobStorageEndpoint" value="http://blob.core.windows.net" value=" http://blob.core.windows.net" /> <Setting name="QueueStorageEndpoint" value="http://queue.core.windows.net" value=" http://queue.core.windows.net" /> <Setting name="TableStorageEndpoint"
ing 127.0.0.1 (localhost) port numbers appear in Figure 4’s Development Storage dialog. YourPrimaryAccessKey is the base64Encoded Primary Access Key value on the Azure Portal’ Portal’ss Project Summary page. Each <Setting name="*Endpoint" … /> element in the ServiceConfiguration.csfg file must have a corresponding entry in the ServiceDefinitio ServiceD efinition.csdef n.csdef file (indicated here in red):
value="http://table.core.windows.net" value=" http://table.core.windows.net" /> --> </ConfigurationSettings> </Role> </ServiceConfiguration>
<?xml version="1.0" encoding="utf encoding="utf-8"?> -8"?> <ServiceDefinition name="SampleWebCloudService" xmlns="http://schemas.microsoft.com/ xmlns=" http://schemas.microsoft.com/ ServiceHosting/2008/10/ServiceDefinition">
Settings for cloud storage services are commented out in the preceding example; local setting values are the same for all users. The <Instances count="3"> element causes three instances to run in the Development or Azure Fabric. Note that the preced-
<WebRole name="WebRole"> <InputEndpoints> <!-- Must use port 80 for http and port 443 for https when running in the cloud --> <InputEndpoint name="HttpIn" protocol="http" port="80" /> </InputEndpoints> <ConfigurationSettings> <Setting name="AccountName"/> <Setting name="AccountSharedKey"/> <Setting name="BlobStorageEndpoint"/> <Setting name="QueueStorageEndpoint"/> <Setting name="TableStorageEndpoint"/> </ConfigurationSettings> </WebRole> </ServiceDefinition>
FIGURE 4 Manage Local Developer Fabric and Storage Instances This multiple exposure screen capture capture shows log data for three t hree instances of this article’s SampleWebCloudService project running in the Development Fabric and emulated Azure Azur e Storage Storage Services Services for blobs,queues, blobs,que ues, and Azure’s schemaless Entry-AttributeValue tables. A local SQL Server Se rver 2005+ Express instance holds a DevelopmentStorageDb mentStor ageDb database to store blobs, queues, and account information information as well as a ProjectName database containing Azure Table Services data. Starting up the Development Fabric and Development Services slows VS’s compile compile and run operations significantly.
18
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
If the <Setting> element name attribute values don’t don’t match in the two files, you receive an “Invalid “Invalid configuration file” message when running in the Developer Fabric; the Azure Azure Fabric adds the names of missing or misspelled <ConfigurationSetti <ConfigurationSettings> ngs> elements. The matching <Setting> name attributes requirement is hidden in an “Issues and Constraints in the Windows Windows Azure Tools Tools and SDK” white paper (see Additional Resource Reso urces, s, p. 25). The <Inp <InputEndp utEndpoint oint> > element element’s ’s port attribute determines whether Azure expects clear-text HTTP or encrypted HTTPS—Secure Sockets Layer (SSL)—protocol. (SSL)—protocol. Setting up HTTPS requires completing completi ng the entries on the SSL page of the ProjectName node’s properties sheet.
Connect to Schemaless Schemal ess EAV Tables with REST Windows Azure tables are similar to the schemaless Entity Ent ity -Attribute-V -Attribute-Value alue (EAV) (EAV) tables of the initial SQL
R E T I R E Y O U R D A TA TA C E N T E R
Server Data Services (SSDS) CTP’s Authority-ContainerEntity (ACE) model, which has been been incorporated into Windows Azure Azure as SQL Data Ser vices (SDS). The EAV EAV data model is much more scala ble than conventional conv entional file system-based relational tables. Azure tables have a distributed architecture that’s related to Google’s Google’s Bigtable, and Microsoft says Azure tables are designed designed to scale scale to billions billions of entit entities ies and terabytes of data. Azure and SDS table versions offer offer free-form “open “open properties” (formerly “flex properties”) or property bags and permit adding or removing table attribute/ attribute/value value pairs pairs at will. How However ever,, the two versions have different required properties and sets of data types. Azure tables require PartitionKey and RowKey string property values to form a concatenated concatenated primary key and automatically add a DateTime Timestamp property value to each entity. entity. SDS entities require require a unique Id property property value, permit an optional Kind property, and supply an autoincrementing autoincrementing Version Version value for concurrency management. FIGURE 5 Stage Azure Apps for Testing before Production Deployment Azuree tables Azur tables support Binary Binary,, Bool Bool,, Date DateTime Time,, Windows Azure’s “Click-Twice” deployment approach lets you test your project in .cloudapp.net URL before placing it in proDouble, Doubl e, GUID GUID,, Int, Long,and String data types; SDS a Staging instance with a private guid .cloudapp.net .cloudapp.net URL. Right-clicking on the Project- offers Base64Binary Base64Binary,, Blob, Boolean, DateTime,Deci- duction with your AccountName .cloudapp.net Publ ish opens a page that lets you browse for mal, and String data types.SimpleDB property values values Name service node and choosing Publish .cspkg package and ServiceConfiguration.cscfg files in are limited to strings and require padding numbers your project ProjectName .cspkg with leading zeros and adding offsets for negative val- the project’s …\ProjectName\bin\Debug\Publish folder. Clicking OK exposes the ues,, whi ues which ch compl complica icates tes clien clientt programm programming ing.. My Hosted Service page with the Staging instance in Allocated mode. Click Run to “Comparing Google App Engine, Amazon SimpleDB, start the staged service, test it with the private URL, click Suspend, and then and Microsoft SQL Server Data Services” blog post click the exchange icon to place it in production. provides a detailed comparison of those three services (see Additional Additional Resources, Resources, p. 25). Azure tables and SDS containers containers are units of consistency Progress Toward Standards and have have a size limit of 2GB; Simpl SimpleDB eDB domains, domains, whic which h correMicrosoft’s data-access teams are moving to standards-based spond approximate approximately ly to Azure tables, hold a maximum of 10GB. RESTful data access protocols at an increasingly rapid pace. Azure tables and SDS containers containers have have strong consistency; consistency; all Azure tables, tables, blobs, and queues have have a REST API, API, while SDS and and observers see the same value immediately after an update; special SimpleDB provide REST and SOAP protocols. protocols. algorithms guarantee consistency consistency over multiple multiple replicas. SimAzure tables and SDS use a new version of the ADO.NET ADO.NET pleDB domains promise eventual consistency after a period w ith Data Services (“ (“Astoria Astoria”) ”) runtime, which supports “open propno new updates, but Amazon doesn’t doesn’t specify the inconsistent inconsistent erties” with the Atom syndication wire protocol protocol and operates window’s maximum duration. with the existing ADO.NET Data Services client libraries and Transactions are crucial for online order processing and tools. Pablo Castro’s Castro’s “ADO.NET “ADO.NET Data Services in Windows other business applications, applications, but neither Azure Azure nor SimpleDB SimpleDB Azure: pushing scalability to to the next level” blog post describes tables currently support transactions.However,the Azure team how the Astoria team modified the runtime to accommodate a promises that their tables will “at some point in the future perdynamic “open properties”provider properties”p rovider for Azure Azure and SDS, in addiform atomic transactions across multiple entities within the tion to the static CLR types defined d efined by the more common Entity same partition.” partition.” Partitions are similar to Bigtable’s tablets with Framework and LINQ to SQL data providers (see Additional some characteristics of the App Engine’s Engine’s entity groups thrown Resources,p. Reso urces,p. 25). in; a single VM or server stores all entities in the table with the The REST API for Azure defines HTTP GET (query), POST same PartitionKey PartitionKey value. (App Engine offers transactions transactions for (create), (create ), PUT (update with properties replaced),MERGE (update entities in the same Entity Group.) The CTP p rovides equality without properties replaced), and DELETE operations on entities. filters only and sorts in PartitionKey/RowKey PartitionKey/RowKey order; inequality Here’ss the GET request header for the second page of the sample Here’ filters and developer-specified secondary indexes for alternative project’ss Customers GridView, project’ GridView, which starts with CENTC as the sorting orders are slated for the release version. CustomerID and RowKey value:
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
19
R E T I R E Y O U R D A TA TA C E N T E R
GET /CustomerTable()?$top=12&NextPartitionKey= Customer&NextRowKey=CE Customer&Ne xtRowKey=CENTC NTC HTTP/1.1 User-Agent: Microsoft ADO.NET Data Services x-ms-date: Fri, 19 Dec 2008 23:37:31 23:37:3 1 GMT Authorization: Authorization : SharedKeyLite oakleaf:Z/KA … 5Yc= Accept: application/atom+xml,application/xml Accept-Charset: Accept-Charse t: UTF-8
$top operator. operator. The Atom-formatted Atom-formatted response body includes xms-continuation-NextPartitionKey and x-ms-continuationNextRowKey continuation tokens to identify the first entity of the next page. Optimistic concurrency concurrency management uses eTags and Timestamp values to detect conflicts with If-Matc If-Match h HTTP headers. Here’ Here’ss the GET response header and abbreviated body of the second GridView page: page:
DataServiceVersion: 1.0;NetFx MaxDataServiceVersion: 1.0;NetFx
HTTP/1.1 200 OK
Host: oakleaf.table.core.windows.net
Cache-Control: no-cache Content-Type: application/atom+xml;charset=utf-8
Azure Table Table and Queue Services require authentication, as do private Blob Services; Services; blobs are the only storage type that can be specified for public access. The Authorization Authorization header’s SharedKeyLite value, shown abbreviated in the preceding request header, is specific to the Astoria Astoria client and is the HMAC-SHA256 HMAC-SHA256 encoding enco ding of this string:
Server: Table Service Version 1.0 MicrosoftHTTPAPI/2.0 x-ms-request-id: x-ms-requestid: 2a109a5d- … f6e x-ms-continuation-NextPartitionKey: Customer x-ms-continuation-NextRowKey: FRANK Date: Fri, 19 Dec 2008 23:37:00 GMT Content-Length: Content-Lengt h: 15691
Fri, 19 Dec 2008 23:37:31 GMT\n/oakleaf/Tables GMT\n/oakleaf/Ta bles <?xml version="1.0" encoding="utf encoding="utf-8" -8"
Queries return a maximum of 1,000 entities and support the
standalone="yes"?> <feed xml:base= "http://oakleaf.table.core.windows.net/" xmlns:d="http://schemas.microsoft.com/ xmlns:d=" http://schemas.microsoft.com/ ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ xmlns:m=" http://schemas.microsoft.com/ ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom xmlns=" http://www.w3.org/2005/Atom "> <title type="text">CustomerTable</title> <id> http://oakleaf.table.core.windows.net/ CustomerTable </id> <updated>2008-12-19T23:37:01Z</updated> <link rel="self" title="Custom title="CustomerTable" erTable" href="CustomerTable" /> <entry m:etag="W/"datetime'2008-129T22%3A10%3A30.2752Z'""> <id> http://oakleaf.table.core.windows.net/ CustomerTable(PartitionKey='Customer', RowKey='CENTC')
FIGURE 6 Try the Live Table Services Sample Project You can run this article’s SampleCl Samp leCloudW oudWebSe ebService.sln rvice.sln project in the Azure Services Platform CTP at oakleaf.cloudapp.net. oakleaf.cloudapp.n et. The Default.aspx page contains a paged GridView that displays 12 Northwind Northwin d Customers records per page and a FormView for inserting new entities ; both controls are bound to an ObjectDataSource that connects to an Azure table. (The project’s FormView is disabled in the public version.) The Count button iterates it erates the entity set; clicking on Delete All Customers deletes the table and Create Customers recreates the table and adds Customer entities. Update Customers toggle the addition or deletion of a plus sign (+) after the CompanyName . The Time textbox displays the elapsed time of the server components of these operations.
</id> <title type="text"></title> <updated>2008-12-19T23:37:01Z</updated> <author> <name /> </author> <link rel="edit" title="Custom title="CustomerTable" erTable" href="CustomerTable(PartitionKey= 'Customer',RowKey='CENTC')" /> <category term="oakleaf.CustomerTable" scheme="http://schemas.microsoft.com/ scheme=" http://schemas.microsoft.com/ ado/2007/08/dataservices/scheme" />
22
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
R E T I R E Y O U R D A TA TA C E N T E R
Windows Azure management features are similar to those offered by RightScale for AWS AWS and employed e mployed by the Google App Engine. <content type="applic type="application/xml"> ation/xml"> <m:properties>
</entry> </feed>
<d:PartitionKey>Customer</d:PartitionKey> <d:RowKey>CENTC</d:RowKey> <d:Timestamp m:type="Edm.DateTime"> 2008-12-19T22:10:30.2752Z </d:Timestamp> <d:Address> Sierras de Granada 9993 </d:Address> <d:City>México D.F.</d:City> <d:CompanyName> Centro comercial Moctezuma </d:CompanyName> <d:ContactName> Francisco Chang </d:ContactName> … </m:properties> </content>
Use LINQ to REST to Query Tables ADO.NET ADO. NET Data Services enables enables a subset of the LINQ Standard Standard Query Operators to compose LINQ queries, which an expression tree translates translates to an HTTP URI. The StorageClient StorageClient library’s library’s TableStorag ableStorage, e, TableSto ableStorageDataServiceC rageDataServiceContext, ontext, and TableStorageDataServiceQuery classes and TableStorageEntity abstract class handle interaction with the ADO.NET ADO.NET Data Ser vices client library (System.Data.S (System.Data.Services.Client) ervices.Client) and implement Azure Table Table Services helper functions for CRUD operation on tables, authentication, and error error handling. You define a TableName DataModel type that implements TableStorageEntity and a TableName DataServiceConte DataServiceContext xt that inherits from TableName DataServiceContext.Next, you instantiate the latter in the Page.Preload event handler w ith a StorageAccountInfo type as its parameter, and create and execute a LINQ to REST query with optional paging as shown here for the sample project:
Feature
Windows Azure (October CTP Instance)
Amazon EC2 Beta (Default Instance)
Host OS
Windows Server 2008 Core, 64-bit
Linux Xen kernel (AKI)
Guest OS
Windows Server 2008 Enterprise, 64-bit
Windows Server 2003 R2, 32-bit
Hypervisor
Hyper-V
Xen
CPU
1.5 - 1.7 GHz x64 equivalent
1.7GHz
Memory
1.7GB
1.75GB
Network
100Mbps
250Mbps
Transient storage
250GB
160GB
Persistent storage
50GB Azure storage (maximum for CTP)
Elastic Block Store (up to 1TB)
Authentication/ Authorization
NET Access Control: LiveID, username/ password, X.509 certs, Information Card
Windows with Authentication Auth entication Services (surcharge)
TABLE 1 Compare Windows Azure October 2008 CTP and Amazon EC2 with Windows Server Beta On Sept. 30, 2008, Amazon.com Inc. announced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003. The default Amazon Machine Image (AMI) creates a 32-bit small instance with IIS, .NET 2.0 SP1, 3.0 SP1, and 3.5 (not SP1), and SQL Server Express 2005. The Azure Services Platform October 2008 community technology preview provides services similar to Amazon EC2 with Windows Server (beta) plus SimpleDB (beta), Simple Storage Services (S3), Simple Queue Services (SQS), and Elastic Block Store. This table compares the Azure CTP instance and Amazon EC2 beta default instances.
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
23
TA C E N T E R R E T I R E Y O U R D A TA
There’s There’ s considerable considerabl e overlap of Azure Table Services and SDS features, which portends a future
conflict confli ct at least as serious as that between LINQ to to Enti ty Framework. Framework. SQL and the Entity // Add the continuation tokens to the GET query protected void Page_Preren Page_Prerender(object der(object sender,
nextLink.NavigateUrl =
EventArgs e)
string.Format("?ct={0}/{1}", nextPartition,
{
nextRow); // This LINQ to REST query gets a page of 12
}
// Customer entities at a time
// Set the customersView DataView's DataSource
// From paging code by Microsoft’s Steve Ste ve Marx
// to the query result customersView.DataSourceI customersVie w.DataSourceID D = null;
var query =
customersView.DataSource customersVie w.DataSource = result;
(DataServiceQuery<CustomerDataModel>) (new CustomerDataServiceContext(account).
customersView.DataBind(); }
CustomerTable.Take(12)); // Get the continuation tokens from the request var cTokens = Request["ct"];
You’ll also need code like this that tha t runs once for each session sess ion in the Global.asax.cs file to create the initial table from your TableName DataModel class:
if (cTokens != null) {
StorageAccountInfo StorageAccou ntInfo account = // ct parameter format is "<partition>/<row>" "<partition>/<row >"
StorageAccountInfo.
string[] tokens = cTokens.Spli cTokens.Split('/'); t('/');
GetDefaultTableStorageAccountFromConfiguration();
var partitionToken = tokens[0];
TableStorage.CreateTablesFromModel
var rowToken = tokens[1]; // These QueryOption QueryOptions s become continuatio continuation n // token query parameters in the request query = query.AddQuer query.AddQueryOption( yOption( "NextPartitionKey", partitionToken) .AddQueryOption("NextRowKey", rowToken); } // Execute the LINQ to REST query var result = query.Execu query.Execute(); te(); // Cast result to a QueryOperati QueryOperationResponse onResponse var qor = (QueryOperationResponse)result; (QueryOperationResponse) result; // Get the continuatio continuation n token values string nextPartition = null; string nextRow = null; qor.Headers.TryGetValue( "x-ms-continuation-NextPartitionKey", out nextPartition nextPartition); );
(typeof(CustomerDataServiceContext), account);
After debugging your project in the SDK’s local Developer fabr ic, copy the ApplicationID from the Live Services and Active Directory Federation section of the Azure Services Development Portal Portal to the Portal Portal page of the CloudService node’s node’s Properties sheet, right-click on the node, and choose Publish to open a window containing your project’s project’s …\bin\Debug\Publish folder. Click on Deploy in the Manage page’s Staging area to open the Staging Deployment page, browse to the ProjectName.cspkg ProjectName.cspkg and ServiceConfiguration.cscfg files to fill the App Package and Configuration Settings text boxes, add a unique name (label) for the project to the Properties text box, and click on Deploy to copy the package and configuration data to a Staging instance (see Figure 5, p. 19). After you test test the role with the private private Web Web site URL, click on the central icon to move the project to Production status and test it with your public accountname .cloudapp.net .cloudapp.net URL (see Figure 6,p. 22). “ClickT “ClickTwice” wice” (once for Staging, Staging, once for Production) Production) deployment of roles to the Azure Fabric is a snap—and much easier than migrating apps to AWS AWS or the GAE.
qor.Headers.TryGetValue( "x-ms-continuation-NextRowKey", out nextRow); if (nextPartition (nextPartitio n != null && nextRow != null) {
24
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
SDS vs. Azur Azure e
There’s considerable overlap of Azure Table There’s Table Services and SDS features, which portends a future conflict conflict at least as serious as that that between betwe en LINQ to SQL SQL and the Entity Entity Framework. Framework. A SQL
R E T I R E Y O U R D A TA TA C E N T E R
The SQL SQL Dat Data a Servic Services es team has promised
for months to support schemas and full-text search in later CTPs. Services Labs incubation project is in the works to align SDS with the ADO.NET Data Services and enable Atom and JavaScript Object Notation (JSON) as wire protocols. The SDS team intends to add more relational-style features to the SDS data model in the future. According to Microsoft partner architect Gopal Kakivaya, “Among the things SQL Data Services will include in the future are improvements in backup and restore, differential b-trees, distributed transactions, geo-replication (synchronous and and asynchronou chr onous), s), distri distributed buted materialize materialized d views, job framework, framework, and distributed queries. queries.”” The SDS team has promised for months to support schemas and full-text search in later later CTPs. SDS probably will become a premium offering, with a substantial surcharge over basic Azure Azure Table Storage. For example,Amazon extracts a $0.60 to $1.20 per instance-hour surcharge for SQL SQL Server 2005 Standard. Standard. (SQL Server 2005 Express comes free with the $0.125 to $1.20 hourly charge for Windows Server 2003 R2 instances.) Amazon’s Amazon’s surcharge for Windows Authentication Authentication Services is $0.25 to $0.60 per instance-hour instanc e-hour,, depending on instance type. That totals $7,344 to $15,552 extra per instance-year.Windows Azure with Azure Table Storage probably will be the price leader that entices enterprises to give Azure Platform Services a serious shot at playing a signifi cant role in their data center expansion plans. VSM Roger Jennings is an independent data-oriented .NET developer and computer book author with more than 1.25 million English copies in print. His books on Microsoft operating systems and data technologies have been translated into more than than 20 languages. Jennings’ Jennings’ss latest book is “Professional “Professional ADO.NET 3.5 with LINQ and the Entity Framework” Framewo rk” (WROX/W (WROX/Wiley iley 2009). He’ He’ss also a Visual Studio Magazine contributing editor and writer for Redmond Developer News, and manages the the OakLeaf Systems blog (oakleafblog.blogspot.com). You can reach him at Roger_ Jennings@compuserve. Roger_
[email protected]. com. ADDITIONAL RESOURCES: Azure Services Platform homepage: tinyurl.com/6lr5nr MSDN homepage for Azure developers: tinyurl.com/65ogcw
“Setting Up the Windows Azure Services Platform: An Illustrated Walkthrough” OakLeaf blog post: tinyurl.com/65wywn Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video (Channel9): tinyurl.com/ tinyurl.com/5tsgvm; 5tsgvm; transcrip transcript: t: tinyurl.com/5vh tinyurl.com/5vhprm prm Video clips of 39 Azure-related sessions at PDC 2008 (Channel9): tinyurl.com/5vd7cr Video clips of eight SQL Data Services-related sessions at PDC 2008 (Channel9): tinyurl.com/638uoo Azure SDK online documentation: tinyurl.com/6yy75b SQL Services Labs home page with planned “incubation” projects for SDS tinyurl.com/5asfdm “Windows Azure Tables—Programming Table Storage” white paper: tinyurl.com/59tlo7 “Windows Azure Tables—Programming Tables—Programming Blog Storage” white paper: tinyurl.com/6785ra “Issues and Constraints in the Windows Azure Tools and SDK” white paper tinyurl.com/4m92h9 The Atom Syndication Format (1.0) specification (IETF RFC 4287): tinyurl.com/ysewpe “Amazon Elastic Compute Cloud (EC2) Running Microsoft Windows Server and SQL Server (Beta)” data sheet: tinyurl.com/4xw9cw “Amazon Elastic Compute Cloud (Amazon EC2)” data sheet: http://tinyurl.com/4bw86s “ADO.NET Data Services in Windows Azure: pushing scalability to the next level” blog post by Pablo Castro tinyurl.com/4ky4x2 tinyurl.com/4ky4x2 “Comparing Google App Engine, Amazon SimpleDB and Microsoft SQL Server Data Services” OakLeaf Systems blog post: tinyurl.com/626td8 “Test Harnesses Compare Amazon EC2 with SQL Server and SimpleDB Performance” OakLeaf Systems blog post: http://tinyurl.com/5ea99x “SQL Data Services (SDS) Test Harness Updated to the Windows Azure Services Platform” OakLeaf Systems blog post: tinyurl.com/58tw7c “Test-Drive SQL Server Data Services” by Roger Jennings: Locator+ Code “Test-Drive VS0807RJ_T “Manipulate Data in the Cloud” by Roger Jennings: Locator+ Code VS0805RJ_T
Windows Azure SDK (October 2008 CTP) download: tinyurl.com/5pha33 GO ONLINE Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP) download: tinyurl.com/58oega Azure Services Training Kit - PDC Preview download: tinyurl.com/5z87ru Register with Microsoft Connect to access Azure services online: tinyurl.com/5urpnv
Use this Locator+ code at VisualStudioMagazine.com to go directly to these relatedresources.
READ & DOWNLOAD VS0902RJ Read this article online and download the SampleWebCloudService project for this article.
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
25
C# CORNER
USING EXPRESSIONS
Use Lambda Expressions for Abstract Delegat Delegates es Lambda expressions are nothing more than convenient conv enient syntax for delegates. So why can’t you use them where the Framework expects a delegate? And more importantly, what can you do about it? BY BILL WAGNER
’ve written before about how much I like lambda expressions and the way type inferences work in C#. I think lambda expressions have have more clarity than the combination of delegate definitions and out-of-band method definitions and the related extra work you have to do only to satisfy the language definitions. But, there are some weaknesses. If a method’s method’s parameters contain the System.Delegate abstract type, using lambda expressions introduces special problems: The C# compiler can’t convert convert a lambda to some not-yet-defined concrete, derived delegate type. Without some extra thought on your part, you you’ll ’ll end up with code that looks like it came from .NET 1.0. I’ll walk you through the exercise exercise of understanding why lambda expressions aren’t immediately convertible conv ertible to abstract delegate ty pes, and how you can convince the compiler to convert the specific delegate type you defined for your use. The solution I’ll describe relies on Windows Presentation Presentation Foundation (WPF) and the System.Windows.Threading.Dispatcher System.Windows.Threading.Dispatcher component,but component, but this is not strictly a WPF issue. The issue described crops up in several several locations in the .NET Framework, Framework, including the Windows Windo ws Forms, Office APIs,and Reflection APIs.You’ll APIs.You’ll be able to follow the approach described in this article when you see it crop up in those other technologies as well. Whenever I use an API in the .NET .NET Framework that has a parameter that’s that’s some form of delegate, delegate,II prefer to use a lambda expression expression instead of a more verbose representation representation.. For example, example, this line of code creates a System.Windows.Threading.Timer that calls the method TickHandler when the timer fires: fires :
I TECHNOLOGY TOOLBOX VB.NET C# SQL Server ASP.NET XML XM L
tick = new System.Threading. Timer Timer((unused) ((unused) => TickHandler());
26
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
M O C . O T O H P K C O T S I Y B N O I T A R T S U L L I
C# CORNER » USING EXPRESSIONS
Whenever you’re you’re not sure what thread you’r you’re e on, you can call
Dispatcher.CheckAccess() Dispatcher. CheckAccess() to determine whether you can access any UI controls. If the body body of the method method were were small enough, enough, I would repla replace ce the TickHa Tic kHandle ndler() r() method method call with with the body body of the method. method. That approach works fine most most of the time,but time, but the same technique technique doesn’t work when the API uses System.Delegate as a parameter.For example, you use the Syste System.Wi m.Windows. ndows.Contro Controls.Dispa ls.Dispatcher tcher.Inv .Invoke() oke() method to marshal calls across threads in WPF: public object Invoke(
I built a WPF timer application to show you how this works, illustrating how a little C# 3.0 can make it easy to work with these older APIs (see Figure Figure 1). The timer is quite simple: simple: You give it a length of time and press start. The background background changes changes from light green, to yellow, yellow, to red as time runs out. Updating the display based on time requires responding to events from a timer. timer. Timers run on background threads, threads, so you’ll run headlong into the problem I described at the outset.
delegate method, params object object[] [] args)
Now consider what happens when you try to use a lambda expression for this call:
Updating the Application The UI handling code is straightforward. The work happens when the timer fires, and the code updates the timer display. display. The update must change the text, and possibly the background for the control. That’s a couple couple quick lines of code:
MyTime.Dispatcher.Invoke(() => DoSomething()); MyTime.Background MyTime.Bac kground = newBrush;
You get the cr yptic error:
MyTime.Content MyTime.Conten t = label;
error CS1660: Cannot convert lambda expression to
The timer runs on a background thread,so you need to marshal the call across the thread boundary using the Dispatcher.Invoke() method. These two lines of code are what you’d you’d want to put in a lambda expression, expression, not the heavy-duty business logic that justifies a method definition. But I said earlier that a lambda doesn’t work with Dispatcher.Invoke. Dispatcher .Invoke. It can, but you need to use a concrete concrete delegate definition. definitio n. Several are defined defined in .NET Framewo Framework rk 3.5. The fact that you can use the built-in delegate definitions and assign them makes this solution less work than might initially appear to be the case. These two lines also require require a pair of paramet parameters: ers: a string for the content and a brush for the background color. color. That means you need to use a delegate definition that takes two parameters and returns void:
type 'System.Delegate' 'System.Delegat e' because it is not a delegate type
You’ll probably wonder what’s going on the first time you see this error. erro r. Of cou course, rse, it’ it’ss a dele delegate gate type, type, right? Well, Well, the compile compilerr isn’t isn’t quite as smart as you are.The are. The System.Delegate System.Delegate type is an abstract type, and the type inference engine can’t infer the number and types of the arguments or the return value for some unknown delegate type derived from System.Delegate.T System.Delegate. To fix this problem, you must create a concrete delegate type and assign your lambda expression to that type. Before you delve delve too far into the distant past and begin writing C# 1.0 code, code,remem remember ber delegate delegate types let you you treat methods as data.
Action< Action <string string, , Brush Brush> > updateTimer updateTimer; ;
After declaring the variable,you can assign the delegate variable to the body of the code you want to execute.You execute.You can use a lambda expression here because Action<T1,T2> is a concrete delegate definition: updateTimer = (label, newBrush) => { MyTime.Background MyTime.Back ground = newBrush; MyTime.Content MyTime.Cont ent = label;
FIGURE 1 WPF Timer Application Running This sample application runs a timer while you practice a presentation. The color changes from green to yellow to red as you run out of time. It’ s a great way to demo cross-thread calls, because the timer runs in a background thread.
};
Now you’ve you’ve got a member variable that points to the block of code that you want to execute when the timer raises its event. All that’s left is to use the delegate definition with w ith Dispatcher.Invoke(): Dispatcher.Invoke():
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
27
C# CORNER
» USING EXPRESSIONS
if (!MyTime.Dispatcher.CheckAccess())
else
{
updateTimer(newLabel, updateTimer (newLabel, next); MyTime.Dispatcher.Invoke(updateTimer,
This process is straightforward, but it’s it’s something that you’ll you’ll do repeatedly,so let’s go a few steps further and make this easier to reuse. There’s a simple pattern at work here. Event handlers can be called from a background thread. You’ll see this behavior when you use timers, when you call Web Web services LEADTOOLS v.16 – .NET, WPF, WCF, asynchronously,and asynchronously,a nd in other common common tasks. WF, C API, C++ Class Lib, COM & more! Whenever you’re not sure what thread you’re Document Form Recognition & Processing Barcode on, you can call Dispatcher.CheckAccess() Dispatcher.CheckAccess() to determine whether you can access any UI controls. tro ls. If you need need to to marshal marshal a call call across across thre th read ad bou bound ndar arie ies, s, yo you u mus mustt use use Dispatcher.Invoke(). Dispatcher.Invok e(). The Dispatcher.Invoke() method avoids several different overloads by Mark-up DICOM Medical Multimedia using a params array for any parameters to the method;; it uses an abstract delegate method delegate type for the code that you want to execute. You want a single method that checks whetherr marshaling is needed. whethe needed. If marsha marshalling is needed, needed, the method method marshals marshals the call; otherwise, otherwise , it calls the method pointed pointed Develop your application with the same robust imaging technologies used by Microsoft, HP, Sony, Canon, Kodak, GE, Siemens, the the US US Air Force and Veterans Affairs to by the delegate. You want that method to Hospitals. appear app ear as if it were were a member member of the SysSysLEADTOOLS provides developers easy access to decades of expertise in color, grayscale, document, medical, vector and multimedia imaging development. Install LEADTOOLS to tem.Windows.Controls.Control class. This eliminate months of research and programming time while maintaining high levels of quality, performance and functionality. enables you to to use the code as if it were part of any control. C# 3.0 give givess you a way way to do do •Image Formats: Formats: All industry standards •Medical Web Viewer Framework: Framework: Plug-in this: extension methods. methods. You need to write a including TIFF, EXIF, PDF, JPEG/JPEG2000, enabled framework to quickly build high DICOM, PCL, DWG and hundreds more. quality,full-featured, web-based medical image few different overloads overloads ofthe of the methods,which •Image Compression: Compression: From standard delivery and viewer applications. JBIG, JBIG2, ABIC, JPEG and CCITT G3/G4 to •Medical Image Viewer: High level display enables you to use them with different numLEAD’s specialized ABC, CMP and CMW control with built-in tools for image mark-up, bers of param parameters: eters: compression. window level, measurement, zoom/pan, cine, newLabel, next);
}
•Display Controls: Controls: Scroll, zoom, pan, magnify glass, brightness/contrast/gamma, window level. •Image Processing: Processing: 200+ filters, transforms and color conversion functions with extended grayscale (10 to 16-bit) support. •OCR/ICR/OMR: OCR/ICR/OMR: Full page or zonal multi-threaded recognition with formatted output including PDF, DOC and TXT for Win32 and x64. •Barcode: Barcode: Read/write all industry standard 1D and 2D barcodes (DataMatrix, PDF417, MicroPDF417, QR Code and more). •Forms Recognition and Processing: Automatically identify forms and extract user filled data. • Document Cleanup/Preprocessing: Deskew, despeckle, line and border removal, registration marks and more. •PDF and PDF/A: PDF/A: Read/write raster and text searchable PDF files. •Annotations: Annotations:Interactive Interactive UI for document mark-up, redaction and image measurement (including support for DICOM annotations). •Grayscale Imaging: Imaging: Display and process signed/unsigned 10-16 bit, 32 bit data.
and LUT manipulation. •DICOM: DICOM: Full Full support for all IOD classes and modalities defined in the 2008 DICOM standard (including Encapsulated PDF/CDA and Raw Data). •DICOM Communications: Full Communications: Full support for DICOM messaging and secure communication enabling quick implementation of any DICOM SCU and SCP services. •WPF (XAML): Viewer, Image List, Annotations, Transitions and WIC Codecs. •AJAX AJAX Web Form Image controls for developing rich web applications. •JPIP JPIP Client and Server components for interactive streaming of large images and associated image data using the minimum possible bandwidth. •Scanning: TWAIN and WIA(32 and 64-bit), autodetect optimum driver settings for high speed scanning. •DVD: DVD: Play, create, convert and burn DVD images. •Multimedia: Multimedia: Capture, play, stream and convert MPEG, AVI, WMV, MP4, MP3, OGG, ISO, DVD and more.
public static class WPFExtensions: { public static voidInvokeIfN voidInvokeIfNeeded( eeded( this Control widget, Action whatToDo) { if (!widget.Dispatcher. CheckAccess()) widget.Dispatcher.Invoke(whatToDo); else whatToDo(); } public static void
LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies. Free 60 Day Evalua Evaluation! tion! www.lea www.leadtool dtools.com s.com/vsm /vsm 800 637637-1840 1840
InvokeIfNeeded<T>( this Control Controlwidget, widget, Action Action<T> <T> whatToDo, T parm)
28
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
C# CORNER » USING EXPRESSIONS
Use this Locator+ code at VisualStudioMagazine.com to go directly to these related resources resources..
{ if (!widget.D (!widget.Dispatcher.C ispatcher.CheckAccess( heckAccess()) ))
READ & DOWNLOAD
widget.Dispatcher.Invoke(whatToDo, parm);
VS0902CC Read this article and download the sample code online.
else whatToDo(parm); } public static void InvokeIfNeeded<T1, T2>(this Controlwidget, Control widget, Action Action<T1, <T1, T2> whatToDo, T1 parm1, T2 parm2) { if (!widget.Dispatcher. CheckAccess()) widget.Dispatcher. Invoke(whatToDo, parm1, parm2); else whatToDo(parm1, parm2); } }
Of cou course, rse, you can exte extend nd this class by adding more overloads with more parameters. It’ It’ss a simple extension. There was a method to the WPF designers’madness: They wanted to make make it as easy as possible to use the Dispatcher object by minimizi mini mizing ng the surface surface area area of the API. API. By using abstract delegates, delegates, and params on the parameter list, this object is usable in the widestt possible wides possible num number ber of of scen scenarios. arios. Any method with any number number of parameters can be used. Howev However, er, that comes with a downdownside. This more abstract API removes removes all type safety,, and this hurts the compiler’s safety compiler’s ability to use type inference to make you more productive. The work around is is to add your own own layer of type-safe extension extension methods that provide a layer between your type safe calls and the more abstract .NET library API. VSM Bill Wagner agner,, autho authorr of “Effec “Effective tive C#” C#” (2004) and “Mor “Moree Effective Effective C#” C#” (2008), both from from Addison-Wesley Addison-W esley Professional,has Professional, has been a commercial software developer for the past 20 years. He is a Microsoft regional director direct or and a Visual C# MVP. MVP. His interests include the C# language, .NET Framework, Framework, and software design.E-mail Wagner at
[email protected].
[email protected].
The LEADTOOLS Competitive Upgrade Call Our Sales Dept. (800) 637-4699 for details. Valid through March 31, 2009. Develop your application with the same robust imaging technologies used by Microsoft, HP, HP, Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affair s Hos pital s.
• • • •
One Company Company For Any Any Imaging Need Need Flexible Licensin Licensing, g, Royalty Free Options Time Tested, Tested, Easy Easy to Use Free Technica echnicall Support Support Document
Form Recognition & Processing
Barcode
Mark-up
DICOM Medical
Multimedia
Chosen by thousands of companies for use in their high volume applications and internal systems.
Free 60 Day Evaluation!
www.leadtools.com www .leadtools.com/vsm /vsm
LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies.
GO ONLINE
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
29
San Francisco Hyatt Regency Embarcadero February 23-27, 2009
Buy One VSLiv VSLive e! Conferen Conference ce Registration Get Registration Get One FREE* Calling All Developers — VSLivee! Is Expecting VSLiv Expecting You You!! Take advantage of this recession busting break—register for VSLive!! and bring a colleague VSLive colleagu e absolutely FREE OF CHARGE CHARGE!! That’s up to an $1,800 savings savin gs to you and your company Join us at VSLive! San Francisco and you can expect these great activities: •
•
Attend the Microsof t MSDN Developer Conference FREE (pre-con event, Monday Feb 23. Space is limited; first come, first served.) Participate in the NEW VSLive! After Dark —an —an informal open ended chat with VSLive! speakers, attendees and industry experts
•
•
•
Listen to amazing speakers in over 80 sessions spanning existing technologies, Microsoft’s newest releases, and yet-to-be-shipped tools Visit the Exhibitor Expo E xpo and VIP Lounge & Game Center (sponsored by ComponentOne) Book signings with some of your favorite technical authors
To view the complete agenda and register for VSLive! go to vslive.com/sf2009
Be sure to use priority code NQ9F14 code NQ9F14 to get the 2 for 1 savings! Brought to you by:
vslive.com/sf2009 Be sure to use priority code NQ9F14 to NQ9F14 to get the 2 for 1 savings! Meet these Experts in Person at VSLive! San Francisco:
2 FOR 1 SAVINGS!
UP TO
1800*
$
Rockford Lhotka on Silverlight , and Building Distributed Apps in .NET 3.5 SP1 Lhotka is principal technology evangelist for Magenic Technologies and the conference co-chair, and a well-known author and magazine contributing editor who speaks regularly at major conferences worldwide.
Richard Hale Shaw on LINQ Shaw has created and chaired numerous technology conferences and is a popular and articulate speaker and writer who is well known for his criticisms of non-functioning developer tools
Aaron Skonnard on “Dublin,” Windows Azure , and What’s New in WCF/WF 4.0 Skonnard is co-founder of the Microsoft .NET training provider Pluralsight and author of numerous books, articles, whitepapers, and courses.
Brian Randell on TFS 2010, Database Design , and Team System 2008 Radell is a well-known soft ware developer, developer, consultant, speaker speaker,, course developer and educator. A senior consultant with MCW Technologies, he writes the Team system column for MSDN Magazine.
Bill Vaughn on ADO.NET 3.5 SP1 SP1 for Visual Studio Studio and SQL Server and and Visual Studio Reporting—Lever Reporting—Leveraging aging the New SQL Server 2008 RDL RD L Technology Vaughn is a 35-year veteran veteran of the computer industry, author of the critically acclaimed book “Hitchhiker’s Guide to SQL Server 2000 Reporting Services” and top expert on Microsoft Visual Studio, SQL Server, Reporting Services and data access interfaces.
Deborah Kurata on Visual Studio and .NET Framework Secrets Deborah Kurata, president of InStep Technologies, .NET expert with over 15 years experience in application architecture, design and development, and author of several books, including “Best Kept Secrets in .NET.”
Dave Bost on Prism , and a deep dive into ASP .NET 3.5 SP1 Bost, who has been a developer and solution architect for over 15 years, is a Developer Evangelist with Microsoft and co-hosts the Thirsty Developer Podcast. *
Choose either the VSLive! Plus Package (Five day all access pass Feb. 23-27), or the VSLive ! Conference Package (Three day pass Feb 24-26). The Buy One Get One FREE offer cannot be combined with other discounts or coupons. The second conference pass must be of equal or lesser value than value than the first conference pass.
ON VB
ITERATORS IN VB
Use Iterators Iterators in in VB VB Now Now Iterators are a crucial part of modern programming, not least because they provide the basis for collection traversal using For Each loops. Language Integrated Query (LINQ) adds to the importance of iterators, as iterators ite rators are the source of IEnumerable(Of T) that forms the backbone of LINQ. Learn how to take t ake advantage of them in your code with several different techniques for creating your own iterators in VB. BY BILL MCCARTHY
n Visual Studio 10,Visual 10, Visual Basic and C# will officially attempt to converge rather than diverge. The two languages are touted by Microsoft to have the same major language features as each other; Microsoft also promises “language parity” and “an “an end to the sibling rivalry. rivalry.” For C#, this means the inclusion of long-standard VB features features such as late binding and optional parameters. For VB,it means the inclusion of multi-e multi-expressi xpression on lambdas and auto properties. properties. This parity is not absolute: For example, C# won’t won’t have XML literals, literals, making VB still the best language language for working with XML. One thing VB is not likely to get in the next next release is iterators. Iterators in C# are a language feature that enables you to write a complete implementation for an enumerable object in a single method. An enumerable object is one that you you can perform For Each loops or LINQ LINQ queries on. Array Arrays, s, Lists Lists,, and Collectio Collections ns are all common common examples examples of enum enumerable erable objects. In fact, enumerable objects are so common common in the .NET Framework that that you rarely need to define your own.Still, it’s important you you understand the basics of what enumerable objects are and how how to create them should the need ever arise. Let’s kick things things off with some common examples for iterators you’ll see in C#.The first is from the C# documentation:
I TECHNOLOGY TOOLBOX VB.NET
SQL Server 2005
public IEnumerable BuildCollecti BuildCollection() on()
M O C . O T O H P K C
ASP.NET
{
O T S I
C#
public int[] items;
for (int i = 0; i < items.Length; i++) {
32
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
Y B O T O H P
ON VB » ITERATORS IN VB OBJECT/RELATIONAL MAPPING WITH LINQ RO SQL
superfluous luous. I have seen many cases where iterator blocks are superf Superfluous Superf luous code is an evil because it adds to the testing and maintenance burdens. yield return items[i]; }
} while (currentCharacter++ < 'z'); }
}
I hope you’re you’re laughing laughing at that sample. If you aren’t, aren’t, some explanation might help you see the humor. The code shows a method that returns an IEnumerable: This is what an iterator is in in C#. The “yield “yield return”statement return” statement indicates what is returned when the code is enumerated with a For Each loop or similar. similar. So, this code iterates iterates over an array and returns each each item in the array. array. In other words, words, it is superfluous and just adds overhead, overhead, as an array is already enumerable. That method could have just returned the array cast to an IEnumerable. You might think that’s just a one-off, bad-code example. Sadly Sadly,, I have seen many cases where iterator blocks are superfluous. Superfluous code is an evil because it adds to the testing and maintenance burdens. But not all cases are superfluous. Bill Wagner Wagner in his December 2008 C# column (“What VB Devs Should Know About C#”) showed a good example of creating an iterator that will give you the letters “a” “a” to “z”as you enumerate it: public static IEnumerable<char> Letters() {
This code code shows an important aspect of iterators: They’re state machines. The variable currentCharacter currentCharacter is modified each each time you enumerate the IEnumerable returned from Letters. To achieve the same result in VB could require some substantial s ubstantial work on your part, but there there are, as they say, say, man manyy ways to skin skin a cat (note: (note: no felines were harmed harmed in the production of this code). For example, you could create create an array of Char, Char,populate populate it,and return that: Dim letters(0 To 25) As Char For i As Int32 = 0 To 25 letters(i) = ChrW(&H61 + i) Next
This will work, but it’s a bit messy. An alternative alternative approach is to to refactor this method. The code inside the For i As Int32 = 0 to 25 loop is an expression in a range, so you can use the Enumerable.Range method as part of a LINQ expression: expression: Dim letters = From i In Enumerable.Range(0, Enumerable.Range(0, 26) _ Select ChrW(&H61 + i)
char currentCharacter = 'a'; do { yield return currentChara currentCharacter; cter;
This is a little better, better, but there are other ways to approach this problem, proble m, as well. A String is in fact enumerable and implements implements IEnumerable(Of Char), so you can simplify everything to a single string declaration: Dim letters = "abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuv wxyz"
FIGURE 1 Create the Interfaces of an Iterator VB doesn’t come
with iterators out-of-the-box, as the next version of C# will, but it’s possible possibl e to create your own, and what wh at you can create is more versatile than the plain-vanilla iterators you’ll be able to create with the next n ext version of C#. These are are the interfaces and the members member s you must implement to create your own iterator iterator..
This alternative certainly seems far more maintainable and a lot more obvious too. Of cours course, e, this example example is a simple one.If it were more more complex, complex, such as fetching values from somewhere or calculating the values,the values, the differences between the solutions become much more meaningful. Both the first and last solution are based on having the complete set of characters in memory to begin with, whereas the solution that uses the Enumerable.Range method loads the characters only when you Enumerable.Rangemethod iterate over the letters. This is often referred to as “delayed “delayed evaluation.” evaluation.” Delayed Delay ed evaluation, or “on-demand “on-demand evaluation” evaluation” as I prefer to call it, is an important important aspect of itera iterators tors and especiall especiallyy of LINQ LINQ.. It’ss also something you need to be wary of when translating C# code It’ to VB or when you look for alternatives to iterators.Typically, iterators.Typically, LINQ expressions and utility methods such as Range provide solutions that have the desired,on-demand evaluation behavior. However, Howeve r, there are times when you will find it necessary to write an iterator. One such case occurred for me recently.I wanted
VisualStudioMagazine.com · February 2009 ·
VISUAL STUDIO MAGAZINE
33
ON VB
» ITERATORS IN VB
to read from a stream line-by-line line-by-line,, search for a substring, and return the the first couple of matches. Unfortun Unfortunately ately,, StreamRe StreamReader ader doesn’t have an iterator that returns each line. Without something that is enumerable, enumerable, you can’t can’t form the basis basis of a LINQ query, query, so you’re you’ re forced to write your query query imperatively. imperatively. That’s not as bad as it might first sound; VB developers were doing this successfully successfully for years before before LINQ LINQ came came along: along: strLine = myStreamRea myStreamReader.ReadLin der.ReadLine e Do While strLine IsNot Nothing
VB
If strLine.Con strLine.Contains(value tains(value) ) Then count += 1 resultList.Add(strLine) If count >= 3 Then Exit Do End If strLine = myStreamReade myStreamReader.ReadLine r.ReadLine Loop
Building the query into the imperative procedural block does work, although it’ it’ss kind of on the ugly ugly side. I look at that that code,
EXTEND THE STREAMREADER CLASS
Module StreamExtensions <Extension() > _ <Extension()> Function Lines(ByVal Lines(ByVa l rdr As TextReader) _ As IEnumerable(Of String) Return New StreamReader StreamReaderLineEnumerato LineEnumerator(rdr) r(rdr) End Function End Module
"once on a stream") End If End Function
Private Function IEnumerator_GetEnumerator() IEnumerator_GetEnumerat or() _ As IEnumerator _ Implements IEnumerable.GetEnumerator Return GetEnumerator GetEnumerator() () End Function
Public Class StreamReaderL StreamReaderLineEnumerator ineEnumerator Implements IEnumerable(Of String) Implements IEnumerator(Of String) Private _rdr As TextReader Private _current As String Sub New(ByVal rdr As TextReader) _rdr = rdr End Sub
''' <summary> ''' Get's an enumerator to read lines from a stream ''' </summary> ''' <returns>IEnumerator(Of String)</returns> ''' <remarks>Can only be called calle d once due to the ''' ''' underlying Not thread thread stream. safe.</remarks> safe.</remarks> ''' <exception cref="InvalidOperationException"> ''' thrown if GetEnumerator is called more ''' than once</excep once</exception> tion> Public Function GetEnumerator() _ As IEnumerator(Of String) _ Implements IEnumerable(Of String).GetEnumerator Static iFirstTime As Int32 If iFirstTime = 0 AndAlso _ Threading.Interlocked.Increment( _ iFirstTime) iFirstTime ) = 1 Then Return Me Else Throw New InvalidOpera InvalidOperationException tionException( (_ "GetEnumerator "GetEnumerato r can only be called " & _
LISTING 1 Most of what you see
Public ReadOnly Property Current() As String _ Implements IEnumerator(Of String).Curr String).Current ent Get Ge t Return _current End Get End Property Private ReadOnly Property IEnumerator_Current() _ As Object Implements IEnumerator.Current IEnumerator. Current Get Ge t Return Current End Get End Property
Public Function MoveNext() As Boolean _ Implements IEnumerator.MoveNext _current = _rdr.ReadLine() Return _current IsNot Nothing End Function Private Sub Reset() Implements IEnumerator.Reset IEnumerator. Reset Throw New NotImplementedException() NotImplement edException() End Sub Public Sub Dispose() Implements _ IDisposable.Dispose 'not implemented End Sub End Class
in the class is boilerplate code, with the two methods of interest being GetEnumera GetEnumerator tor and the MoveNex MoveNextt method. This sample also illustrates ill ustrates how to add an extension method to make getting the t he enumerator a lot simpler. The extension method will show up on an instance of the t he StreamReader class as a Lines function.
34
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
ON VB » ITERATORS IN VB OBJECT/RELATIONAL MAPPING WITH LINQ RO SQL
and it screams to me that it needs to be beautified. I’m not the type of person who tends tends to talk about beautifying beautifying code—the May 2007 On VB column headline, “Beautify Your Your Code,”was created by an editor—but an extension extension method is the kind of thing that can help you add some beauty to this code. If you have an extension extension method named Lines that returns returns an IEnumerable with each item a line, then you can create a query like this:
static class StreamExten StreamExtensions sions { static public IEnumerable<String> Lines( this TextReader rdr) { String line; while ((line = rdr.ReadLine()) != null) { yield return line;
Dim result = From line In myStreamReade myStreamReader.Lines r.Lines _
}
Where line.Contains(value) _ Take 3
}
I think that approach is a clear winner for the most beautiful solution. The difficulty is in creating the Lines extension method.If you don’t mind having a C# assembly as a reference,it’s a simple task to create an Extension method that’s an iterator:
VB
}
This can take substantially substant ially more work in VB.You have to implement IEnumerable(Of IEnumer able(Of T) and IEnumerator(Of IEnumerator(Of T), which also includes includes the non-generic IEnumerable, IEnumerator, IEnumerator,and and IDisposable interfaces. That’ss a class That’ class (or classes) classes) with at least seven members, eight if you
CREATE A GENERICITERATOR CLASS
Public Class GenericIterator(Of T) Implements IEnumerable(Of T) Implements IEnumerator(Of T) Public Delegate Function MoveNextFunc( _ ByRef nextItem As T) As Boolean Private _Current As T Private _func As MoveNextFunc Public Sub New(ByVal func As MoveNextFunc) _func = func End Sub
Public Function MoveNext() MoveNext( ) As Boolean _ Implements IEnumerator.MoveNext Return _func(_Current) End Function
Public Function GetEnumerator() _ As IEnumerator(Of T) _ Implements IEnumerable(Of T).GetEnumer T).GetEnumerator ator Static iBeenCalled As Int32 If (iBeenCalled = 0) AndAlso _ (Threading.Interlocked.Increment( _ iBeenCalled) = 1) Then Return Me Else Return New GenericIterator(Of T)(_func) End If End Function
Public ReadOnly Property Current() Current () As T _ Implements IEnumerator(Of T).Current Get Ge t Return _Current End Get End Property Public Overridable Sub Reset() _ Implements IEnumerator.Reset Throw New NotImplement NotImplementedException( edException( _ "Iterator cannot be reset") End Sub
Private Function _ IEnumerator_GetEnumerator( IEnumerator_G etEnumerator() ) As IEnumerator _ Implements IEnumerable.GetEnumerator Return Me.GetEnumerator End Function Private ReadOnly Property IEnumerator IEnumerator_Current() _Current() _ As Object Implements IEnumerator.Current IEnumerator. Current Get Ge t Return Me.Current End Get End Property Public Sub Dispose() _ Implements IDisposable.Dispose ' not implemented End Sub End Class
LISTING 2 This class is most useful in VB10, where you can pass in a multi-statement multi-stat ement lamba expression for the MoveNextFunc. You can use this
generic template template in VB8 VB8 and VB9, but without with out support for multi-statement mult i-statement lambdas you’ll find fin d that you’ll need to use AddressOf, Add ressOf, and capture variables used by making them field s of a wrapper class. As a consequence, you’re better off using the direct implementation ( Listing 1, opposite page) rather than th an the generic template templat e for versions of VB prior to VB10.
VisualStudioMagazine.com · February 2009 ·
VISUAL STUDIO MAGAZINE
35
ON VB
» ITERATORS IN VB
include the constructor include constructor (see Figure 1, p. 33). The good news is that most of these methods are typically implemented implemented with the same boilerplate code.This means that you can streamline creating iterators in VB by using techniques techniques such as snippets, templates, or generic classes. You must implement three methods for the IEnumerator
N e w 7 .0 7 0 e g m a I m D o t I a s e e e l e R
interface: interfac e: Mo MoveN veNext, ext, Rese Reset, t, and Current, Current, a ReadOnly ReadOnly property property.. Reset is seldom used. It can’t can’t be used inside a For Each loop, loop, so for most of your implementations implementations you can Throw a NotImpleNotImplementedException mentedEx ception as the body body of the Reset method. method. The important method is MoveNext. MoveNext. In the MoveNext MoveNext method, you determine whether whether there there are more more items to return. return. If ther theree are, you store the next item to return in the Current property. property. This means the Current Current property needs to return only a field. Next, add the generic interface IEnumerator(O merat or(Off T). Then add Curre Current nt As T, T, a strongly typed ReadOnly Property, Property, as well as an IDisposable.Dispose implementation.At this point, you have have two ReadOnly properties named Current that won’t compile, or you have one named Current and the other other named Current1. Current1. A good way to deal with this is to make the least strongly stro ngly typed meth method od Privat Private. e. This allows you to give the method a name for internal use. You can still access the private method externally through a cast to the interface: Private m_Current As T Public ReadOnly Property _ Current() As T _ Implements IEnumerator( _
The .NEx .NE xT Step In Document and Photo Imaging
Of T).Current Get Return m_Current End Get End Property
DotImage 7.0—More Powerful, with Zero-Footprint Imaging, and 3 Months of Free Gold Support.
Private ReadOnly Property _ IEnumerator_Current() _ As Object _
New features to our already powerful imaging toolkit include PDF/A support, AJAX Vect Vector or Annotations including FreeHand, WPF annotations, and more. Use templates in our AJAX Wizard to create zerofootprint web applications in C# and VB.NET—Take document and photographic imaging to the .NExT step. Visit Atalasoft.com Atalas oft.com for fo r web demos, video tutorials, and a free f ree trial.
Atalasoft , Your .NET Imaging Partner Atalasoft, Par tner Call us toll free at 866-568-0129 www.atalasoft.com
36
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
Implements IEnumerator.Current Get Return Current End Get End Property
You must also implement IEnumerable(Of T). This includes includes a single functio function n (GetEnumerator), (GetEnu merator), in which you return return your IEnumerator(Of IEnumerator(Of T) implementation. As part of the IEnume IEnumerabl rable(Of e(Of T) interinterface, you must also implement implement the nongeneric IEnumerable IEnumerable interface. IEnumerable also has a GetEnumerator function,
ON VB » ITERATORS IN VB OBJECT/RELATIONAL MAPPING WITH LINQ RO SQL
The VB version is obviously lengthier than the C# version, but the VB version has some significant benefits. but its return type is the non-generic IEnumerator. As you did with the Current property and IEnumerator,make the IEnumerable GetEnumerator method Private and have it call the more strongly typed generic method: Public Function GetEnumerator() _ As IEnumerator(Of T) _ Implements IEnumerable( _ Of T).GetEnumer T).GetEnumerator ator 'TODO: add implementation here End Function Private Function _ IEnumerable_GetEnumerator() _ As IEnumerator Implements _ IEnumerable.GetEnumerator Return GetEnumerator GetEnumerator() () End Function
The code you put inside the GetEnumerator method deserves careful consideration. You need to think through t hrough how you expect expec t these implementations implementations to be used, used, as well as how they will behave in cases such as multi-threaded environments or when changes occur. occur. Enumerators are normally considered to be a snapshot. For example, List(Of T)’s enumerator enumerator will throw a runtime exception exception if the list is changed during a For Each iteration. Other iterators might just ignore changes. In the case of a stream, your decision is a bit tougher. You change a stream’s strea m’s position as you read from from it. For example example,, if ther theree are two iterators reading reading from the one stream, the results could be unpredictable, unpredictable, changing depending on threading behaviors. behaviors. There are two ways around around this problem: problem: Use a null stream and have the iterators return no data, or throw an exception in GetEnuGetEnumerator if it has been been called previously previously.. Throwing an exception makes it easier to debugg what debu what went wrong wrong.. Whi Whichev chever er choice you make, make, take the time to docudocument it by completing the XML comments on the method:
VisualStudioMagazine.com · February 2009 ·
VISUAL STUDIO MAGAZINE
37
ON V B » ITERATORS IN VB
''' <summary>Get's an enumerator to read lines ''' from a stream </summary> ''' <returns>IEnumerator(O IEnumerator(Of f String) </returns> ''' <remarks> Can only be called once due to the ''' underlying stream. ''' Not thread safe. </remarks> ''' <exception cref="InvalidOperationException"> ''' thrown if GetEnumerator is called more than once ''' </exception> Public Function GetEnumerator() As IEnumerator( IEnumerator(Of Of String) String) _ Implements IEnumerable( IEnumerable(Of Of String).GetEnumerator String).GetEnumerator Static iFirstTime As Int32 If iFirstTime = 0 AndAlso _
and combine this with a generic template to give you the same functionality from VB. To do this, you need to define a delegate in your generic template that has the current current item as a ByRef ByRef parameter: Public Delegate Function MoveNextFunc( _ ByRef nextItem As T) As Boolean
Your generic iterator takes a delegate in its constructor,stores a reference to to it, and calls that in the MoveNext MoveNext method. Once you define the GenericIterat GenericIterator or class (see (see Listing 2, p. 35), you can use this much as you you use inline iterators in C#. For example, you can create a line-by-line iterator with a StreamReader:
Threading.Interlocked.Increment(iFirstTime) = 1 Then Return Me Else Throw New InvalidOpera InvalidOperationExcepti tionException( on( _ "GetEnumerator "GetEnumerat or can only be called once on a stream" ) End If
Dim lines = New GenericIterator(Of String) _ (Function(ByRef (Function(By Ref nextItem As String) As Boolean nextItem = rdr.ReadLin rdr.ReadLine e Return nextItem IsNot Nothing End Function)
End Function
There are a couple of points worth discussing in this code. code. The code relies on a static variable inside the code to check whether the method has been called previously previously,, and uses Threading.InterThreading.Interlocked.Increment locked.Inc rement to change the value. This ensures that it can be called calle d only once, once, even in a thread-ra thread-race ce conditio condition. n. If it has been called more than once, an InvalidOperationExcep InvalidOperationException tion is thrown. Note that the method returns a Me reference when called for the first time. This is because the class implements both the IEnumerable(Of T) interface and the IEnumerator(Of T) interface.You can separate them into different classes, but often it’s useful to have have them in a single class because you generally need to store some shared state in them them (see Listing 1, p. 34, for a complete complete example of a StreamReaderLineEnu StreamReaderLineEnumerator). merator). The VB version is obviously lengthier than the C# version, but the VB version version has has some significant benefits. First, your implementat ion is likely to be more robust because you’ve been forced to look at the implementation details. Second, the C# version doesn’t prevent GetEnumerator being called more than once on the same stream. This could result result in some obscure obscure threading problems. problems. It could also produce seemingly null result sets for files if the iterator is called called twice. Or,it could potentially potentially result in some object-disposed exceptions occurring that aren’t explicit in describing the real problem. The C# version does provide a quick-and-dirty way to write the iterators: The quick part is inviting, but it’s often often the dirty part that we spend a lot more time cleaning up after. It’s important to note that iterators iterato rs in C# aren’t always dirty. Sometimes they do provide an elegant and clean clea n way to express an IEnumerable. IEnume rable. And it’s it’s likely VB will get a similar syntax in the not-too-distant not-toodistant future. future. In VB10, VB10, you will be able to use multimultistatementt lambdas that captur statemen capturee surrounding variables.If you you’re ’re willing to accept the same limitations that iterators have in C#, then you can use a lambda as the basis for the MoveN MoveNext ext method
38
VISUAL STUDIO MAGAZINE · February 2009 · VisualStudioMagazine.com
The lack of a formal syntax for iterators iter ators in VB doesn’t mean you you can’t create iterators iterators in VB.In fact, the download for this article includes includes a snippet,templates,and snippet, templates,and examples of how you can write iterators easily in the current version version of VB. VB.The The download also includes an example that illustrates how to use a generic template and lambdas in VB10. Using the downloadable snippet or templates in the current version of VB, you can quickly create iterators that are more flexible and more robust than what the C# iterator syntax allows for. As LINQ and PLINQ become become more a part of your programprogramming, your reliance on iterators will increase, so now’s a good time to learn how to write them properly. properly. Being exposed to the implementation details will give you a better understanding of iterators and their pitfalls, which means you’ll you’ll be less likely to yield to the temptation of using them poorly when the day comes comes that VB too adds some syntactic sugar for creating iterators. So grab these downloads and start writing your own iterators today. VSM Bill McCarthy is an independent consultant based in Australia and is one of the foremost .NET language language experts specializing in Visual Visual Basic. He’ He’ss been a Microsoft MVP for VB for the last 10 years and sat in on internal development reviews with the Visual Basic team for the last five years where he helped to steer the language’s future direction.These days he writes his thoughts about language direction on his blog at http://billmccarthy.com.
GO ONLINE Use this Locator+ code at VisualStudioMagazine.comto go directly to these related resources.
READ & DOWNLOAD VS0902OV Read this article and download the sample code online.
Advertising Sales
Ad Index Atalasoft, Inc.
36
www.atalasoft.com
dtSearch
12
www.dtsearch.com
East
ESRI
Andrew Mintz National Sales Manager
www.esri.com
Phone: 508-532-1433
[email protected]
Intel Corporation
LEAD Te Technologies, In Inc.
Microsoft Account Manager Danna Vedder Phone: 253-514-8015
[email protected]
28, 29
www.leadtools.com
Chris Kourtoglou Regional Sales Manager Phone: 415-814-0955
[email protected]
William Smith Phone: 603-886-3466
[email protected]
C4
www.intel.com
West
National Accounts Director
7
Microsoft Corporation
20, 21
www.microsoft.com
Director, Print Production
Pegasus Im Imaging Co Corporation
37
www.pegasusimaging.com
Jenny Hernandez-Asandas Phone: 818-734-1520 ext 101 Fax: 818-734-1528
[email protected]
Software FX Inc.
Production Coordinator
TallApplications BV
Catharine Wood Phone: 818-734-1520 ext 233
[email protected] [email protected]
TallComponents BV
C2, 1
www.softwarefx.com
2
www.deepseaobfuscator.com
C3
www.tallcomponents.com
Visual Studio Magazine
ID Statement Visual Studio Magazine (ISSN 1537-002X) is published
monthly by 1105 Media, Inc., 9121 Oakdale Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals postage paid paid at Chatsworth, CA 91311-9998, and at additional mailing offices. Complimentary subscriptions are sent to qualifying subscribers. subscribe rs. Annual subscription rates rates for for non-qualified subscribers are: are: U.S. $34.97, Canada $52.97 (U.S. funds); International $78.97 (U.S. funds). Subscription inquiries, back issue requests, and address changes: Mail to: Visual Studio Magazine, P.O. Box 1164, Skokie, IL 60076-8164, email VSM@1105servi
[email protected] ce.com or or call call toll free 888-768-8759, fax number 847-763-9564. International Interna tional to callVisual calls s 847-7639135. POSTMASTER: Send address changes Studio Magazine, P.O. P.O. Box 1164, Skokie, IL 60076-8164. Canada Publications Mail Agreement Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or Bleuchip International, P.O. Box 25542, London, ON N6C 6B2.
Copyright Statement © Copyright 2009 by 1105 Media, Inc. All rights reserved. Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to "Permissions Editor," c/o Visual Studio Magazine, 230 California St., San Francisco, CA 94111.
Legal Disclaimer The information in this magazine has not undergone any formal testing by 1105 Media, Inc. and is distributed withwithout any warranty expressed or implied. Implementation or use of any information contained herein is the reader's sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar
9
www.visualstudiomagazine.com
results may be achieved in all environments. Technical inaccuracies may result from printing errors and/or new developments in the industry.
Corporate Address Corporate Headquarters: 1105 Media 9121 Oakdale Ave. Ste 101 Chatsworth, CA 91311 www.1105media.com
VSLive! San Francisco
30, 31
www.vslive.com/2009/sf
Wayside Technology Group Inc.
5
www.waysidetechnology.com
Edit Ad Index Combit GmbH
Media Kits Direct your Media Kit requests to:
www.combit.net/en
Matt Morollo, VP Publishing Phone: 508-532-1418 Fax: 508-875-6622 E-mail:
[email protected]
DataDirect Technologies
11
11
www.datadirect.com
MadCap Software
13
www.madcapsoftware.com
Reprints Reprints: For single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact: PARS International Phone: 212-221-9595 E-mail:
[email protected] Web: www.magreprints.com/QuickQuote.asp
List Rental This publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone: 914-368-1000 E-mail:
[email protected] Web: www.meritdirect.com
Resco
12
www.resco.net
Go to VisualStudioMagazine.com to access the stories in this issue, plus read exclusiv exclusive e online-only content.
VisualStudioMagazine.com · February 2009 · VISUAL STUDIO MAGAZINE
39
The Th e Hu Huma man n
Factor
WHERE DID ALL THE DEVELOPERS DEVEL OPERS GO? GO?
BY DANIEL APPLEM APPLEMAN AN
Goog le Trends Google Trends (trends.google.com) is a curious tool. It displays the relative popularity of searc search h terms ove overr time.Rec time. Recently ently,, a group of develo developers pers on a software-developers software-de velopers forum noted that over over the past five five years, years, searches for VB.NET have been declining to the point p oint where they are now and degrees granted in computer science s cience programs have been below those for C#. dropping recently. recently. This year many colleges (including top-tier This, Thi s, of co cours urse, e, mea means ns nothi nothing. ng. Fo Forr one thin thing, g, Vi Visua suall programs such as MIT, MIT, Rutgers, and Berkeley) report lower Basic programmers use more than one search term (VB, enrollment.Carnegie Mellon, one of the top computer science VB.NET,, Visual Basic),while C# programmers use only C#,so schools in the country, VB.NET country, had only 2,000 applicants for its comtotal VB searches, while trending downward,are probably still puter science department, down from 3,200 in 2001. well above C#. Besides, the whole VB versus C# discussion is Google Trends Trends is little more than a curiosity, a signpost to tiresome—the framework framework is where the real excitement excitement is. If reality reality.. The surge of people who entered entered programming in the C# use is growing at the expense ofVB.NET ofV B.NET,, who cares? ’80s is drifting away. away. Fewer people are entering entering the field. The Except that it isn’t isn’t growing. The real surprise in the trend software development development world has fragmented, with programline was that C# searches have been flat for years. This prompts mers being drawn from mainstream-development platforms the question:If programmers are leaving leaving VB and aren’t aren’t going to new technologies such as iPhone and Facebook application to C#, where are they going? Could it be that they’re abandon- development (both of which are trending trending upward). ing Microsoft technologies? There’ss another reality to be found on Google Trends. There’ Trends. It I checked the trend lines for other programming lan- also lists the regions, cities, and languages where a search term is guagess and platforms, incl guage including uding PHP, PHP, Pe Perl, rl, Java Java,, Jav JavaScri aScript, pt, most popular. Keeping in mind that language terms are most and Flash programming. I discovered that C#, by holding flat, popular with beginners and those learning a new language, it’s is doing well because every other “traditional” language is interesting to note that the top three regions for C# are India, trending downward. South Africa, Africa, and Israel (the (the United United States is No. No. 10), that the Why would this be? Perhaps developers are using seven top cities are in India and China,and that the No.1search Live.com instead of Google? I’d accept that if it were just the language is Chinese.Indeed,similar region and language trends trends Microsoft languages,but LAMP programmers leaving Google apply across every language and dev platform I checked. for Live.com? I don’t don’t think so. Something real is happening. Where have all the coders gone? Now we know. know. But perDoes use of language names as search search terms correspond correspond haps the better question is: Where are the new coders going to to the popularity ofa of a language? After After all,experienced all,exper ienced developers come from? That’s something you can help answer,by answer, by teaching don’t often search for language names—we’re names— we’re much better at your kids ki ds to code and an d by volun teer ing to help hel p introdu intr oduce ce or refiningg our searches. Peopl refinin Peoplee use language names as search teach programming in your local schools and community terms when they’re curious about them or when they’re just col colleges leges.. And if you aren aren’t ’t part of crea creating ting the answer answer,, don don’t ’t starting out. They use them to find introductory articles and complain if you don’t like like the answer you get. VSM tutorials. So we’re most likely likely looking at a specific population; new developers and those who are switching languages. Could Dan Appleman is a Microsoft Visual Basic MVP, MVP, webmaster of the declining trend lines be indicating an overall drop in interest Searc SearchDotN hDotNet.com,CEO et.com,CEO of Desaware Desaware Inc, co-fou co-founder nder of Apre Apress, ss, in computer programming? Could to it newer indicate a movement away from traditional programming platforms? It’ss probably both. Statistics from the U.S. It’ U.S. Department of Education and National National Science Board concur: concur: Enrollment
40
VISUAL STUDIO MAGAZINE
· February 2009 · VisualStudioMagazine.com
and sometime author author, , speaker speaker, , andtalk blogger who haswithout throughout his career insisted that you can’t technology also discussing its human and financial impact. You can reach him at
[email protected].
EVOLVE YOUR CODE. Parallelism breakthrough. Anal An alyz yze, e, com ompi pile le,, de debug bug,, ch chec eck, k, an and d tu tune ne yo your ur co code de fo forr mu mult ltic icor ore e with Intel® Parallel Studio. Designed for today’s serial apps and tomorrow’s parallel innovator innovators. s. Learn more and sign up for Beta: www.intel.com/go/parallel
© 2009, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and other countries. *Other names and b rands may be claimed as the property of others.