VisualStudioMagazine.com

It’s Here. What Does It Mean?

( Hint: If you’re an ASP.NET developer, a lot.)

PLUS New Column! Papa’s Perspective ASP.NET Distributed Caching Razor View Engine with Visual Basic Volume 21, No. 9 Volume SEPTEMBER 2011 NetAdvantage®

REPORTING, DATA VISUALIZATION AND LOB UI CONTROLS FOR ASP.NET, WINDOWS FORMS, JQUERY/HTML5, WPF, SILVERLIGHT AND WINDOWS PHONE 7

INFRAGISTICS MOTION FRAMEWORK™ Delivering a great user experience in Windows Presentation Foundation (WPF) and Silverlight business intelligence applications requires more than styling, it requires giving your application's end users greater insight into the story of their data.

OLAP PIVOT GRID DATA VISUALIZATION Work with multidimensional data from your OLAP cubes, data warehouses and Microsoft® SQL Server® Analysis Services.

Untitled-7 2 7/8/11 12:22 PM ASP.NET GAUGE Whether it's for a sidebar gadget or an internal portal such as SharePoint®, gauges play a crucial role on any dashboard.

WINDOWS FORMS GANTT CHARTS Deliver a Microsoft Project-style user experience to your users, with the composite tabular/timeline view of your scheduling data.

CHARTING jQUERY Make business charting quick The most robust and easy with fast, interactive, and forward- and vivid visuals across every thinking product .NET platform. we have based on emerging Web technologies including HTML5 and CSS 3. EXPORT TO MICROSOFT® WORD New class library can create Word documents and stream xamGrid™ contents from Silverlight to a Word document. SILVERLIGHT DATA VISUALIZATION Use the Silverlight Data WINDOWS PHONE 7 Visualization treemap Visually and functionally control to communicate designed to build eye- differences in data points catching, high-end user with different pattern experiences that take your identifications. mobile applications to the next level on the Microsoft® Windows Phone® 7.

SCAN HERE for an exclusive look at Ultimate! www.infragistics.com/ult

TAKE YOUR APPLICATIONS TO THE NEXT LEVEL WITH OUR TOOLS INFRAGISTICS.COM/ULTIMATE

Infragistics Sales 800 231 8588 • Infragistics Europe Sales +44 (0) 800 298 9055 • Infragistics India +91 80 4151 8042 • @infragistics

Untitled-7 3 7/8/11 12:22 PM techxtend.com 866-719-1528

Embarcadero RAD Studio XE2 UltraEdit VMware vSphere 5 The ultimate application development suite The world’s #1 text editing solution Essentials Kit Bundle for Windows, Mac, mobile and Web is also the world’s most affordable! VMware vSphere is the industry-leading virtualization platform for building cloud by Embarcadero by IDM Computer Solutions infrastructures that enables users to run Embarcadero® RAD Studio XE2 Professional is UltraEdit is the world’s standard in text business critical applications with designed for software developers and teams editors. Millions use UltraEdit as the ideal confidence and respond faster to building PC, Mac, kiosk and mobile applications text/hex/programmers editor on any their business. platform — Windows, Mac, or Linux! with or without embedded and local database vSphere accelerates the shift to cloud NEW persistence. RAD Studio includes Delphi®, NEW Features include syntax highlighting computing for existing datacenters, while VERSION VERSION! C++Builder®, and RadPHP™ providing you Named User for nearly any programming language; also underpinning compatible public cloud 5! with everything needed for fast native powerful Find, Replace, Find in Files, 1-24 Users offerings paving the way for the only Windows, Mac OS X, .NET, PHP, Web and Paradise # hybrid cloud model. With over 250,000 Professional Ed. and Replace in Files; FTP support, sort, iOS development. customers worldwide and the support of Paradise # column mode, hex, macros/scripting, I84 01201A01 large file handling (4+ GB), projects, over 2500 applications from more than CGI 15501A01 $ 95 templates, Unicode, and more. 59. 1400 ISV partners, VMware vSphere is CALL the trusted platform for any application. CALL techxtend.com/embarcadero techxtend.com/idm techxtend.com/vSphere Spread 5 for Windows Forms Kingston DataTraveler G3 TX Text Control 16.0 by GrapeCity PowerTools 16 GB Flash Drive Word Processing Components • World’s best selling .NET Spreadsheet by Kingston Technology TX Text Control is royalty-free, robust and • Import/export native Microsoft Excel files The new generation of a Kingston powerful word processing software with full formatting in reusable component form. New best-seller is here! With capacities up Version • Extremely flexible printing and export options to 32GB, the reliable DataTraveler Generation 3 • .NET WinForms and WPF rich Released! including PDF (G3) is ideal for your important documents, text box for VB.NET and C# • Extensible formula support, including music, video clips and favorite photos that can • ActiveX for VB6, Delphi, VBScript/HTML, ASP Microsoft Excel functions be stored and retrieved in a flash. • Hundreds of chart styles for enhanced data • File formats DOCX, DOC, RTF, HTML, Professional Edition Available in four fun colors by capacity, it’s a visualization XML, TXT Paradise # perfect fit for the office, home, school and • Powerful user interface and flexible data • PDF and PDF/A export, PDF text import T79 12101A01 connectivity wherever you travel. A well-built cap protects Paradise # Upgrade the USB plug and your data. DataTraveler G3 • Tables, headers & footers, text frames, $ 99 • WYSIWYG spreadsheet designers, quick-start ZHI DQ1077 bullets, structured numbered lists, multiple 1,109. Paradise # also makes a great promotional item for wizard and chart designers undo/redo, sections, merge fields, columns F02 01101A01 your organization. $ 99 Download a demo today. • Royalty-free licensing 28. • Ready-to-use toolbars and dialog boxes $ 99 936. techxtend.com/grapecity techxtend.com/kingston techxtend.com/textcontrol Lenovo ThinkPad X220 HP Laserjet Professional 2010 by Lenovo P4014N Printer by Microsoft The ThinkPad X220 features the quality by Hewlett Packard Microsoft Visual Studio 2010 Professional with and performance Lenovo users have Get reliable, fast, and affordable black- MSDN Essentials Subscription is an integrated come to expect and increased audio, and-white printing for your workgroup! environment that simplifies creating, debugging video and communications features that With print speeds of up to 45 pages per and deploying applications. Unleash your respond to the increased use of laptops minute (ppm) and a 540 MHz processor, creativity and bring your vision to life with as a multimedia and communications the HP LaserJet P4014 will help your powerful design surfaces and innovative tools in business. The ultra-portable workgroup operate at peak efficiency. collaboration methods for developers and ThinkPad X220 comes equipped with a Get consistent results and optimal performance Paradise # designers. Work within a personalized environ- full-powered Intel processor with outstand- with the printer’s latest advancements in toner ZHI R83053 ment, targeting a growing number of platforms, ing graphic performance. ThinkPad has technology. Legendary HP reliability means improved on full-size keyboard design and Paradise # Upgrade including Microsoft SharePoint and cloud worry-free printing that stands up to the $ 99* nimble TrackPoint by adding an advanced ZHI GF0818 671. Paradise # applications and accelerate the coding process demands of your office environment. by using your existing skills. buttonless touchpad. M47 40201B02 $1,362.99 $599.99* $ 99 483. techxtend.com/microsoft techxtend.com/lenovo techxtend.com/hp * Offer expires 9/30/11 Datawatch Monarch Professional 11.0 Programmer’s Paradise has a new name: TechXtend! by Datawatch For nearly 30 years, Programmer’s Paradise has served the software development and IT communities with the No other desktop software tool provides best selection of software, terrific values and a commitment to service excellence. Excel-based Business Intelligence (BI) and reporting as easily as Monarch. 30 years... much has changed in that time! Monarch lets anyone, regardless of technology However, one thing that won’t ever change is that we’ll still be your “go to” source for software developer skill level, acquire, customize and export data to tools — AND you'll also be able to depend on TechXtend for all of your other IT needs. Excel and other applications. Unlike traditional BI and reporting solutions, Monarch uses Report Learn more about our new name: www.techxtend.com/techxtend Mining to very easily acquire actionable data business users need, with no programming Win an iPad! skills required. Paradise # NO PURCHASE NECESSARY. Use offer code WEBTRW09 when you place your order online or with your TechXtend/ D07 04201E01 Programmer’s Paradise representative and you’ll automatically be entered into a drawing to win an iPad Wi-Fi 32GB. $ 99 For official rules, or to complete the online entry form: www.techxtend.com/tradewinds 952. techxtend.com/datawatch Software, Systems, & Solutions – Since 1982 Prices subject to change. Not responsible for typographical errors.

Untitled-2 1 8/1/11 11:20 AM { FRAMEWORKS }

12

Keith Ward, Editor in Chief, Visual Studio Magazine Papa’s Got a Brand New Mag You’ll probably notice a different face at the top of this column. It’s no longer Mike Desmond’s handsome mug, but my far September 2011 // Volume 21 // No. 9 inferior one. Mike did an amazing job with VSM, and I’ll do my best to pick up where he left off. I look forward to getting to know FEATURES you; interactions with readers have always 12 HTML5 for ASP.NET Developers been one of the best parts of my job, and The technologies bundled as HTML5 finally support what developers have your feedback—both positive and negative— been trying to get HTML to do for decades. BY PETER VOGEL can only help the magazine get better. 17 Scale ASP.NET Apps Through Distributed Caching Mine isn’t the only new face you’ll fi nd in If you’re developing an ASP.NET application for a high-transaction environment, these pages this month. I’m giddy to you can use distributed caching to boost performance without major changes introduce our new columnist, John Papa. to your code. Here’s what you need to know to get started. BY IQBAL KHAN He’ll be familiar to many of you, especially developers who write Web-based 28 LANGUAGE LAB applications. Papa is a senior technical evangelist for Microsoft (the title “Evangelist” PRACTICAL .NET PAGE 28 never ceases to tickle me), the author of 10 Dynamically Loading Classes at Runtime books and 70-plus articles (many for MSDN Sometimes you want to be able to decide what classes you’re going to load at runtime. You’ve got two choices in the Microsoft .NET Framework to implement Magazine, for which he wrote the Data dynamic loading, including the Managed Extensibility Framework. But the Points column a few years back), and a designdecisions you make are equally as important. BY PETER VOGEL go-to guy for XML, Silverlight, Windows Presentation Foundation, C#, .NET, SQL ON VB PAGE 37 Server, HTML5 and more. Basically, if it’s Using Razor with Visual Basic Internet or mobile, Papa has it covered. ASP.NET MVC 3 and the Razor view engine are powerful methods for building Web applications. This tutorial shows you how to build a Web site using those His arrival couldn’t have come at a techniques within Visual Basic. BY JOE KUNK more crucial time. The Microsoft BUILD conference is this month, and it could be MOBILE CORNER PAGE 42 historically important. Rarely has the Windows Phone 7 Data Binding with Templates Redmond gang been faced with the kind of Nick Randolph walks through Windows Phone 7 data binding and how you challenges presented by smartphones, can use templates to create customized lists. BY NICK RANDOLPH tablets, mobile apps and the “post-PC era” that Steve Jobs recently predicted was on DEPARTMENTS its way (I think Jobs is wrong, but he still 6 Letters to the Editor carries the biggest bullhorn in the business). Still, Microsoft needs to answer the DevDisasters 7 questions its developers have—questions A Bit Unwise BY MARK BOWYTZ (THEDAILYWTF.COM) like “What’s happening to Silverlight?”; “Is 8 DevInsights VSTOOLBOX, PAPA’S PERSPECTIVE HTML5/JavaScript/XAML really the future?”; VSToolbox: Client-Side Data Management with NetAdvantage for jQuery PAGE 8 “What exactly is ‘Windows 8,’ and how do I Papa’s Perspective: Effective JavaScript Tips PAGE 9 prepare for it?” How Microsoft answers these inquiries will help shape its future. COLUMNS What do you think the future holds for you and your dev environment? Tell me at 3 Frameworks BY KEITH WARD [email protected]. 48 Redmond Review BY ANDREW J. BRUST

VisualStudioMagazine.com · September 2011 · VISUAL STUDIO MAGAZINE 3 Online Contents

Get the complete picture —the latest dev news, analysis and REDDEVNEWS.COM ADTMAG.COM

how-to content—at Microsoft Dynamics AX 2012 Why Wall Street Programmers VisualStudioMagazine.com Integrates More Managed Code Earn the Big Bucks BY KURT MACKIE BY DAVID RAMEL and our partner sites Microsoft released its Dynamics AX 2012 In high-frequency trading (HFT), in the Redmond enterprise resource planning software in programmers eke out every last August, touting features that will enable incremental tick in performance to build Developer Network. greater customization by developers algorithms that battle other algorithms for and partners. computational supremacy and millions in profi ts. David Ramel looks inside the world EASY FINDIT RedDevNews.com/Mackie0911 of HFT, where coders earn top dollars. What we once called FindIT codes are now easy URLs. You’ll see these embedded HTML5 Reality Check: ADTmag.com/Ramel0911 throughout Visual Studio Magazine so you can Tools and Strategies You Can Use Today access any additional information quickly. BY TODD ANGLIN Adobe Releases HTML5 Animation Tool Simply type in VisualStudioMagazine.com/ Let the pundits debate Flash versus BY CHRIS PAOLI followed by the FindIT code into your URL Silverlight versus HTML5—developers need Adobe released a preview version of its address field. (Note that all URLs do not have any spaces, and they are not case-sensitive.) to build software and want the real story. upcoming HTML5 development tool called HTML5 offers many benefi ts to developers Adobe Edge. Designed to create animated that are usable today with the right tooling Web content with JavaScript, HTML and and adoption strategies. CSS, the preview version was downloaded over half a million times in fi rst 24 hours. RedDevNews.com/Anglin0911 ADTmag.com/Paoli0911 LightSwitch: Turned off by VISUALSTUDIOMAGAZINE.COM the Silverlight Client? Red Hat’s Mark Little on the BY KATHLEEN RICHARDS Big Picture for Java Take Advantage of XML Comments (Part 2) Visual Studio LightSwitch 2011 is described by BY JOHN K. WATERS BY JOE KUNK Microsoft as a self-service development tool Java has the potential to emerge as a On VB columnist Joe Kunk continues his for people who want to build data-centric, dominant language supporting Platform as examination of XML comments by extending line-of-business applications. Is the Silverlight a Service. John K. Waters discusses the next the XML comment vocabulary with front-end a reason to hesitate? Developers era in Java with Mark Little, senior director additional default tags in Visual Basic. Find weigh in. of engineering in the Red Hat JBoss group. out how to process the resulting XML fi le into API-style reference documentation using the RedDevNews.com/Richards0911 ADTmag.com/Waters0911 SandCastle Help File Builder.

VisualStudioMagazine.com/Kunk0911 ID Statement Visual Studio Magazine (ISSN 1537-002X) is published monthly by 1105 Media, Inc., 9201 Oakdale Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals postage paid at Chatsworth, CA 91311-9998, and at additional mailing offi ces. Complimentary subscriptions are sent to qualifying subscribers. Annual subscription rates payable in U.S. funds for non-qualifi ed subscribers are: U.S. $35.00, International $60.00. Annual digital subscription rates payable in U.S. funds for non-qualifi ed subscribers are: U.S. $25.00, Windows Phone 7 Orientation Primer International $25.00. Subscription inquiries, back issue requests, and address changes: Mail to: Visual Studio Magazine, P.O. Box BY NICK RANDOLPH 2166, Skokie, IL 60076-7866, email [email protected] or call toll free (888) 768-8759, fax number 847-763-9564. Interna- tional calls 847-763-9135. POSTMASTER: Send address changes to Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866. Nick Randolph walks you through how to Canada Publications Mail Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or XPO Returns: defi ne, change and work with orientation P.O. Box 201, Richmond Hill, ON L4B 4R5, Canada.

within Windows Phone 7 applications. Copyright Statement © Copyright 2011 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. VisualStudioMagazine.com/Randolph0911 Suite 302, San Francisco, CA 94111.

Legal Disclaimer The information in this magazine has not undergone any formal testing by 1105 Media, Inc. and is distributed Enable Coded Builds with Windows without any warranty expressed or implied. Implementation or use of any information PowerShell and psake contained herein is the reader’s sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar results may be achieved in all environments. Technical BY IAN DAVIS inaccuracies may result from printing errors and/or new developments in the industry. There’s a lot of work going into the migration Corporate Address 1105 Media, 9201 Oakdale Ave. Ste 101, Chatsworth, CA 91311 www.1105media.com from XML- and GUI-based build systems Media Kits Direct your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), to coded build scripts using tools like Rake, 508-875-6622 (fax), [email protected] Albacore, FAKE and psake. Open Source .NET Reprints For single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact: columnist Ian Davis explores creating domain- PARS International Phone: 212-221-9595 E-mail: [email protected] www.magreprints.com/QuickQuote.asp specifi c languages to run coded builds. List Rental This publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, VisualStudioMagazine.com/Davis0911 please contact our list manager, Merit Direct. Phone: 914-368-1000; E-mail: [email protected]; Web: www.meritdirect.com.

4 VISUAL STUDIO MAGAZINE · September 2011 · VisualStudioMagazine.com Untitled-1 1 7/19/11 3:34 PM Check out our events at VSLive.com We’ll be at Microsoft HQ and in Orlando in 2011

VisualStudioMagazine.com Letters September 2011 • Volume 21 • No. 9 Editorial Staff Vice President, Doug Barney Editorial Director Andrew Brust offered his take on Visual Studio LightSwitch, a new line-of-business Editor in Chief Keith Ward Executive Editor Kathleen Richards application development tool that breaks the mold of traditional dev platforms and Managing Editor Wendy Gonchar frameworks, in his August column, “LightSwitch: The Answer to the Right Question.” Associate Managing Editor Katrina Carrasco Readers shared their views on LightSwitch and its use of Silverlight. Tools Editor Peter Vogel

I’m a longtime developer who has done everything from assembler to Web apps, Contributing Editors Andrew J. Brust, Ian Davis, Mickey Gousset, and I must say I’m impressed by what I’ve seen of LightSwitch. I can see using it to Roger Jennings, Joe Kunk, Jeff Levinson, Mark Michaelis, John Papa, Karl E. Peterson, rapidly bootstrap applications for my clients and then using a combination of its Nick Randolph, Patrick Steele, Eric Vogel extension points to provide the customization they’ll inevitably want. Quality of Art Staff the result and rapid productivity are what my customers want, and I can see Creative Director Scott Shultz LightSwitch giving me a very big boost in delivering them. The other major thing I Art Director Joshua Gould like about LightSwitch is that it may fi nally propel Silverlight into the mainstream Production Staff of development where it belongs. Director, Print Production Jenny Hernandez-Asandas Production Coordinator Serena Barnes Bryan Morris Online/Digital Media Director, Online Media Becky Nagel I want to use apps on my iPad. It’s been a year—why is Silverlight required? Executive Editor, New Media Michael Domingo Ted Newherd Site Administrator Shane Lee Designer Rodrigo Muñoz

Advertising/Sales In his July cover story, “Levels of TFS Build Automation,” Benjamin Day showed VP, Publishing Matt Morollo Regional Sales Manager Chris Kourtoglou readers how to take advantage of the latest build functionality in Microsoft Team National Accounts Director William Smith Foundation Server (TFS) 2010 using an incremental process that he dubbed “levels of Microsoft Account Manager Danna Vedder build awesomeness.”

President Henry Allain This is by far the best article I’ve found after weeks of sorting through all the Vice President, Publishing Matt Morollo details available about TFS functionality. The practical, step-by-step approach Director of Marketing Michele Imgrund makes the information provided easy to retain and take action on. Thank you! Online Marketing Director Tracy Cook Name Withheld

President & Neal Vitale Chief Executive Offi cer VSM Tools Editor Peter Vogel served up 17 free Visual Studio tools in “Visual Studio Senior Vice President Richard Vitale & Chief Financial Offi cer Toolapalooza” in June. Readers weighed in on their own choices for SMTP servers. Executive Vice President Michael J. Valenti

Senior Vice President, Abraham M. Langer smtp4dev is unstable, in my opinion (and I read quite a lot of opinions similar to Audience Development mine). This is an open source alternative: papercut.codeplex.com. & Digital Media Vice President, Christopher M. Coates Name Withheld Finance & Administration Vice President, Erik A. Lindgren Information Technology I always love a good tool review. For SMTP, I’ve been using Free SMTP Server for & Application Development testing and sending e-mail—and yes, it actually sends the e-mail. I wish it had a log, Vice President, Carmel McDonagh Attendee Marketing but you do get to watch the program window refl ect the operation (softstack.com/ Vice President, David F. Myers freesmtp.html). Sounds like this and papercut would be a good combination ... Event Operations Name Withheld Chairman of the Board Jeffrey S. Klein

REACHING THE STAFF Staff may be reached via e-mail, telephone, fax, or mail. A list of editors and contact information is also available online at VisualStudioMagazine.com. E-mail: To e-mail any member of the staff, please use the following form: [email protected]. Irvine Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. PT) Visual Studio Magazine wants to hear from you! Send us your thoughts Telephone 949-265-1520; Fax 949-265-1528 about recent stories, technology updates or whatever’s on your mind. 4 Venture, Suite 150, Irvine, CA 92618 E-mail us at [email protected] and be sure to include Framingham Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. ET) Telephone 508-875-6644; Fax 508-875-6633 your first and last name, city and state. Please note that letters may be 600 Worcester Road, Suite 204, Framingham, MA 01702 edited for form, fit and style. They express the views of the individual Corporate Offi ce (weekdays, 8:30 a.m. - 5:30 p.m. PT) authors, and do not necessarily reflect the views of the VSM editors or Telephone 818-814-5200; Fax 818-734-1522 1105 Media Inc. 9201 Oakdale Avenue, Suite 101, Chatsworth, CA 91311

Visual Studio Magazine The opinions expressed within the articles and other contents 6 VISUAL STUDIO MAGAZINE · September 2011 · VisualStudioMagazine.com herein do not necessarily express those of the publisher.

{ SOFTWARE DEVELOPMENT GONE WRONG }

A Bit Unwise

“Wait a second—only after the price of diesel reaches four bucks a input4 = true;

gallon does anybody notice a bug in the fuel effi ciency reports?” if (input4 == true && input5 == true && ignition == false) John C. asked incredulously. description = "Engine Stopped, Oil Pressure Low (Mechanical Failure)"; “Yep. We’re talking about old Calvin code,” his manager said. else if (input4 == false && input5 == true && ignition == false) description = "Engine Stopped, Ignition ON (High water temperature)"; John’s employer sold vehicle fl eet tracking units. The company’s else if (input4 == true && input5 == false && ignition == false) founders hired Calvin to write the fi rmware that ran on the vehicles description = "Engine Switched OFF"; else if (input4 == true && input5 == true && ignition == true) and the receiving applications on the server side. description = "Engine Runnning";

Forbidden Territory return description; } John wished that the problem was with the reports, or any part of the code developed after the Calvin era. No such luck: The problem was Calvin’s C# server-side code—specifi cally, the part responsible Real Magic for determining the engine’s running status. John dove into the logic as pressure from the customers mounted. Everybody agreed that Calvin was smart, but he liked to show off. Every time he made some headway on regression testing—different Why limit yourself to true and false when magic numbers like 319 vehicles had their own magic numbers, of course—something and 329 would do? And despite his “wizard” status, he seemed to would break. On the verge of throwing his PC out of the nearest have a tenuous grip on the concepts of binary, hex and bitwise logic. window and making a break for it, John experienced a After tracking down the code responsible for detecting the breakthrough. Could there have been some real genius after ignition status, John knew he would be in for a headache later on: all in Calvin’s magic numbers? public string inputDescription(int iDec) { John grabbed a calculator and a list of ignition codes, and sure int numbase = 2, base10 = 10, MaxBit = 32; enough, the solution was easy. Calvin had just taken the long route: if (iDec == 0) return "Engine OFF"; public static string inputDescription (int iDec) char[] cHexa = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' }; { int[] iHexaNumeric = new int[] { 10, 11, 12, 13, 14, 15 }; bool ignition = (iDec & 2) != 0; int[] iHexaIndices = new int[] { 0, 1, 2, 3, 4, 5 }; bool input4 = (iDec & 8) != 0; string strBin = "", description = "Engine OFF";; bool input5 = (iDec & 16) != 0; int[] result = new int[32]; for (; iDec > 0; iDec /= numbase) String description = "Engine OFF"; { int rem = iDec % numbase; if (input4 && input5 && !ignition) result[--MaxBit] = rem; description = "Engine Stopped, Oil Pressure Low (Mechanical Failure)"; } else if (!input4 && input5 && !ignition) for (int i = 0; i < result.Length; i++) description = "Engine Stopped, Ignition ON (High water temperature)"; if ((int)result.GetValue(i) >= base10) else if (input4 && !input5 && !ignition) strBin += cHexa[(int)result.GetValue(i) % base10]; description = "Engine Switched OFF"; else else if (input4 && input5 && ignition) strBin += result.GetValue(i); description = "Engine Running"; strBin = strBin.TrimStart(new char[] { '0' }); return description; bool ignition = false, input4 = false, input5 = false; } After testing, John was satisfi ed his own “magic” had won the if (strBin.Length == 2 || strBin.Length > 2) if (strBin.Substring(strBin.Length - 2, 1) == "1") day. Unfortunately, that was only one function down—there were ignition = true; hundreds to go. VSM else ignition = false; if (strBin.Length == 4 || strBin.Length > 4) if (strBin.Substring(strBin.Length - 4, 1) == "1") Tell Us Your Tale input5 = true; else input5 = false; Mark Bowytz is a contributor to the popular Web site The Daily WTF if (strBin.Length == 5 || strBin.Length > 5) (thedailywtf.com). He has more than a decade of IT experience and is if (strBin.Substring(strBin.Length - 5, 1) == "1") currently a systems analyst for PPG Industries. Have you experienced input4 = true; the darker side of development? E-mail your tale to Executive Editor else Kathleen Richards at [email protected].

VisualStudioMagazine.com · September 2011 · VISUAL STUDIO MAGAZINE 7

NetAdvantage for jQuery

Infragistics Inc. VSToolbox Web: Infragistics.com Phone: 800-231-8588 Price: $995; $1,495 with Client-Side Data Management with Priority Support Quick Facts: A set of JavaScript NetAdvantage for jQuery libraries that includes a dozen jQuery Infragistics provides a toolkit for creating data-driven applications using client-side extensions aimed at managing data code that accesses a variety of data sources, both in the page and back on the client. Pros: Includes a client-side data source manager, a grid and a range BY PETER VOGEL libraries that extend jQuery. Here, the jewel of editors for accepting data The primary focus of NetAdvantage for in the crown is the Infragistics igDataSource Cons: Help support not jQuery is a set of extensions to the open control. The igDataSource, similar to the jQuery well integrated

Extensions source JavaScript library for creating ASP.NET DataSources, makes a variety of data-driven applications that can access data look alike. With the igDataSource, you data on the server (through services) or can retrieve data from Web Services and a date picker, an upload control and a embedded in the page. But, in some ways, (returning JSON or XML), RESTful video player. The controls will be familiar NetAdvantage for jQuery is an odd services, arrays, HTML tables and most of to anyone used to working with jQuery UI package. Infragistics has included several the client-side objects holding data that you’d Widgets. Styling support is based on the non-client, .NET, server-side resources: want to display. This flexibility lets you create jQuery UI CSS Framework and can use libraries for managing XPS and PDF pages that combine a variety of data sources themes generated by the jQueryThemeRoller documents and for working with both Word into a single display. The igDataSource can tool. The package also includes support for and Excel files. Other components that go cache data locally so that you can provide accessibility and internationalization. beyond jQuery are a better fit for the filtering and sorting at the client. A simple call Installation was easy: I just downloaded product’s title—namely, a set of ASP.NET to the igDataSource SaveChanges method the package from the Infragistics site and MVC helpers to facilitate generating pushes changes back to the data source ran the installerEXE file to install every- client-side code for jQuery extensions, and (where the data source supports updating). thing. If you’d prefer not to add the the necessary libraries to integrate the While the igDataSource is the key part of Infragistics JavaScript libraries to your extensions into ASP.NET MVC applications. the package, jQuery for NetAdvantage also application, you can use the company’s But what a developer is looking for in a includes almost a dozen editing controls, Content Delivery Network. client-side jQuery package are JavaScript including a grid, a text editor, a date editor No documentation is installed on your computer or integrated into the Visual Studio help system. You’ll find a link to documentation in your Windows Start menu (once you drill down far enough) that leads to the general introduction to all of the Infragistics help and related resources. After finding the help for the package, you’ll want to add two bookmarks to your browser: one for the developer’s guide and another to the API documenta- tion. Several demos are included in the download, but for direction on using them with ASP.NET MVC, ADO.NET Data Services or Windows Communication Foundation .svc files in an ASP.NET application, you’ll need to visit the Infragistics Web site. Infragistics provides a trial download so that you can make sure you’re comfortable working with the package before buying it. VSM

Peter Vogel is the Visual Studio Magazine tools Creating a Grid: In this simple page, the drop-down list is loaded from the server, but when the editor and a principal at PH&V Information user selects an entry the grid is loaded from client-side code using the igDataSource and igGrid. Services, specializing in ASP.NET development.

8 VISUAL STUDIO MAGAZINE · September 2011 · VisualStudioMagazine.com 0911vsm_GrapeCity_Insert.indd 1 8/10/11 11:45 AM 0911vsm_GrapeCity_Insert.indd 2 8/10/11 11:46 AM

Papa’sPerspective BY JOHN PAPA Effective JavaScript Tips JavaScript can be unwieldy. But using techniques like separation and Revealing Module Pattern can get it under control.

technologies. I’ll show a simple timer but as a general rule I recommend keeping application and offer a few tips to make the styles in one place (my preferred your JavaScript more manageable. location is their own CSS file). You can see the separation of the HTML,

Separation CSS and JavaScript in the three files: JavaScript First let’s take a look at the sample Timer.html, Styles.css and Timer.js. Development application (Figure 1), a simple timer with I made two other separation changes as buttons for starting, pausing and resetting. well. First, I removed the embedded style on The code for this article has a file named buttonSurface and moved it to Styles.css, TimerAllInOneFile.html, which contains which is arguably more maintainable. I also the HTML structure for the timer, the CSS removed the embedded event handlers and that styles it to look like Figure 1 and the assigned them in code in the Timer.js file, JavaScript to make it function. The file as shown here: does a pretty good job of separation, but function init(startButton, pauseButton, clearButton) { this is a simple example with only a few document.getElementById(startButton). Welcome to the first article of my new dozen lines of HTML, CSS and JavaScript. addEventListener( column, Papa’s Perspective—and thanks You can download the sample code from "click", startTimer, false); for reading it! VisualStudioMagazine.com/Papa0911. document.getElementById(pauseButton). As this is the first of the series (and The problem with this approach is that addEventListener( because my editor ordered me to introduce the code can easily become more difficult to "click", pauseTimer, false); myself), I’ll spend a quick moment sharing manage. For example, scripts could be document.getElementById(clearButton). a little about me and my vision for this created in line with HTML structure or addEventListener( column. Some of you may know me anywhere in the HTML file. In general I "click", clearTimer, false); through my books, articles, watching find it easier to maintain and debug code displayTimer(); Silverlight TV on Channel 9, speaking at when I know the JavaScript is in one place }; conferences or on Twitter (@john_papa). If separated from the HTML. Most browsers’ you do, you know that I value good debuggers support debugging JavaScript The Fight Against Global Variables development practices, speaking in terms files, but they don’t all support debugging All JavaScript variables share a single everyone can relate to and being casual. script code in HTML files: global namespace. They’re created

within the global scope or whenever a JavaScript gets a bad rap sometimes for
implicit declaration of variables, because variables that can easily be confused with
very difficult. This can make it easier to and cats and dogs living together can all
maintaining JavaScript difficult. But it
doesn’t have to be that way. I’ll say it plainly: You may notice that the buttonSurface JavaScript can be productive and fun. DIV has an embedded style. This is an easy This month I’ll discuss a common trap to fall into when all of your code is in technique to separate structure (HTML), one file. Having embedded styles, styles in behavior (JavaScript) and presentation the same page in a STYLE tag and linked (CSS) with modern Web development. styles can make it difficult to diagnose This type of separation is commonly problems with presentation. Sometimes accepted as a good practice with other there are valid reasons to override styles, Figure 1. A simple JavaScript timer.

VisualStudioMagazine.com · September 2011 · VISUAL STUDIO MAGAZINE 9

Papa’sPerspective

collide with same-named variables (your own or ones in other script file code) and to lose track of the lifetime. Figure 2 shows the Internet Explorer 9 debugger displaying the functions and variables used by Timer.html and Timer.js, all of which are in the global namespace. It’s conceivable that the HTML page might use another script file that might have a variable named init, seconds or any of the

JavaScript JavaScript other members listed in Figure 2. There are Development two easy ways to avoid globals: declaring variables within your own namespace and enclosing your variables within a module. Namespaces are easy to create and often used by popular libraries like jQuery Figure 2. The Internet Explorer 9 debugger, displaying the program’s functions and variables. (which uses $) and KnockoutJS (which is declared. Notice TimerRMP is declared immediately (self- instancing), as shown in uses ko). For my main application, I like to and set to be a function, and then all the the last line of the TimerRMP.js code: create a namespace called my, which can be code below it is pretty much the same: } (window)); done easily using the following code: var TimerRMP = (function (window) { Notice that window is being passed into var my = my || {}; var the function. This allows the window For simpler apps I don’t always use timerId = -1, object to be explicitly set to a variable namespaces. But I do use modules quite often, interval = 25, inside of the function and thus avoids any specifically the Revealing Module Pattern. ms = 0, assumption that that variable exists. Some seconds = 0, say this is unneeded, while others like how The Revealing Module Pattern minutes = 0, clean it is. Also, if you prefer to turn on the The Revealing Module Pattern helps startTimer = function () { strict option for your JavaScript, you can encapsulate similar logic and avoid if(timerId === -1) { add the “use strict” to the first line inside of polluting the global namespace. The idea is timerId = window.setInterval( your function. simply to wrap all related logic in a module "TimerRMP.turnTimerOn()", interval); and only expose or reveal the parts of it that } Benefi ts of Separation and the need to be accessible outside of the module. }, Revealing Module Pattern The basic way to use this pattern is to create The pattern is called Revealing because I’ve found it valuable to use separation a function that wraps all of the JavaScript the module reveals only the functions patterns, whether it be Silverlight with logic, and return an object from this returned from the object. Notice that the Model-View-ViewModel, ASP.NET with function that contains the functions that only functions exposed by the function are MVC or even for unit testing. I don’t need a need to be accessible outside your module. init and turnTimerOn. fancy acronym for JavaScript separation to This pattern is quite easy to implement. This means that the only variable added to know it’s a good thing for maintainability, Simply create a variable and set it to an the global namespace is TimerRMP, and the testing and debugging. Along with empty function. Then put your JavaScript only functions exposed are TimerRMP.init separation, I find that the Revealing Module code inside that function, as shown here: and TimerRMP.turnTimerOn. This is a Pattern is easy to follow, reduces variables in var TimerRMP = function () { dramatic reduction from all the global the global namespace and makes it simple /* your JavaScript code goes here */ namespace pollution in Timer.js. Code to encapsulate logic in a way that makes }(); outside of the module can’t access the other sense. Plus, it keeps JavaScript clean. And As an example, take a look at the variables and functions because they’re that is Papa’s Perspective. VSM complete code in TimerRMP.js. The same now hidden inside the module’s enclosure: JavaScript in Timer.js has been copied to return { John Papa is a senior technical evangelist for TimerRMP.js, then used inside of the init: init, Microsoft. He’s the author of 70-plus articles and function that’s set to the variable TimerRMP. turnTimerOn: turnTimerOn 10 books, and specializes in professional The following code shows the beginning }; application development with Microsoft of TimerRMP.js, which specifically The TimerRMP variable is set immedi- technologies. He can be contacted via johnpapa.net demonstrates how the TimerRMP variable ately because the function is called or followed on Twitter at twitter.com/john_papa.

10 VISUAL STUDIO MAGAZINE · September 2011 · VisualStudioMagazine.com Untitled-2 1 6/29/11 11:42 AM VSM COVER STORY

HTML5 for ASP.NET Developers

The technologies bundled as HTML5 fi nally support what developers have been trying to get HTML to do for decades. BY PETER VOGEL

Microsoft’s announcement that HTML5 Getting Set Up All you have to do to enable a page for processing as HTML5 is add and JavaScript would be first-class tools for creating this doctype declaration at the top of your site’s Master Page: ‘Windows 8’ applications created consternation among some .NET developers. Would their investments But, because HTML5 is a collection of technologies rather than a monolithic block, different browsers will have different parts of in XAML and Silverlight be wasted? Would they HTML5 implemented. To use HTML5 but fall back gracefully be forced to work with HTML/JavaScript instead when a browser doesn’t support what you need, add Modernizr (an of compiled, data-typed languages? Besides, hadn’t open source JavaScript library for checking for HTML5 and CSS3 support) to your toolset (modernizr.com). we heard all this before with Active Desktop for Internet Explorer 4, which enabled HTML on the Declarative Forms Windows desktop? And isn’t it dead? HTML has never provided the range of tools that developers expect from standard Windows development tools. HTML5 helps close Not dead; maybe just reborn. At the Windows 8 unveiling in May, that gap. For instance, in HTML5, you can have a combobox—just Microsoft Corporate Vice President Julie Larson-Green, who oversees declare a textbox using the input element and then tie it to a datalist the Windows client, said the announcement meant that developers element using the new input tag’s new list attribute: “can write new applications for Windows using the things that they’re doing already on the Internet.” That’s the point: HTML and JavaScript are tools for Internet development. And, for ASP.NET developers, the nologies can be repurposed to be used in desktop and smartphone Many features implemented in Windows Forms with a property development … well, that’s very nice—but it’s secondary. setting require the intervention of JavaScript in HTML. Tools often What’s new in HTML5-related technologies is direct support for fea- disguise that: “setting a property” in ASP.NET, for instance, often tures that developers take for granted in other environments—there’s generates both HTML and JavaScript (the SetFocus and AutoPost- more that can be done declaratively without having to drag in JavaScript back properties being the most obvious examples). HTML5 doesn’t (“just set an attribute”), there’s more support for data structures and eliminate the need for JavaScript, but it does reduce it, simplifying there’s more support for typical line-of-business (LOB) activities. And life both for Web developers and tool developers by replacing what ILLUSTRATION BY RYAN ETTER RYAN BY ILLUSTRATION that’s ignoring what you can do with CSS3 (a topic for a different article). used to require code with declarative settings.

12 VISUAL STUDIO MAGAZINE · September 2011 · VisualStudioMagazine.com VSM COVER STORY

The workhorse input element demonstrates that movement best. Within a section element, the traditional header tags (h1, h2 and To begin with, in HTML5 the input element has far more states. In so on) now define the structure of the content rather than the text’s addition to the already existing states (text, password), HTML5 format; the new hgroup element represents the introduction mate- adds number, datetime, email, url and a half-dozen more. The new rial for a section. A figure element marks a section of material that required attribute prevents a page from being submitted until the “belongs together” (for instance, a video or image element with its element is provided a value. accompanying figurecaption element). These changes mean that All by themselves, these two changes reduce the need for ASP.NET you can stop using CSS classes to flag your document’s structures developers to use Validator controls, while providing a new way for and start adding styles for the dedicated elements. Validator controls to implement their functionality without requiring Developers have been creating menus in Web pages using a variety JavaScript. The new autofocus attribute causes the focus to switch to the of hacks, but HTML5 adds explicit support for menus. The menu element when the page is first displayed, eliminating the need for the tag specifies a menu with nested command elements that display JavaScript behind the SetFocus property. And, of course, developers text tied to JavaScript functions: clicking on the command ele- appreciate the additional datatyping control on the input element. ment’s text runs the JavaScript function specified in the element’s But wait, there’s more. If you’re working with numeric fields, onclick event. You can also use a command element outside of a then the step, max and min attributes provide further declarative menu element as a target for a hotkey (the command element’s text control over the user’s data entry; on text fields, the pattern attribute won’t be displayed) to have it run code when the user presses the allows you to apply a regular expression to the user’s input. If you correct key combination. Menus can also be used as context menus: want to display a prompt string in a text box, you can add the new just assign the menu an id and use that id in the contextmenu placeholder attribute and set it to the string to be displayed. attribute of some other element. A typical input tag that exploits these changes might look like the Most ASP.NET developers will probably continue using the following code. This sample defines a numeric-only textbox that ASP.NET Menu control, but that control can now implement its must have a value, and will only accept single digits between 1 and functionality using the new menu and command elements. This 9 (and only the integers in between): has real benefits; for instance, tying menus to the browser should Putting it all together, a typical Master Page using the new structure Many of these new attributes are not tied to specific elements but elements and an HTML5 menu might look like Listing 1. In addition are considered global attributes. The new contenteditable attribute, to defining a menu within the nav element, this example makes for instance, can be applied to any element to prevent the user from the menu available as a context menu from the footer at the bottom changing the content of that element. of the form. The HTML button elements acquire new attributes (formaction, Structured Pages formmethod) that allow the button to control how a form is to be In the past, developers have used div and span tags as structural ele- submitted. These new elements transfer control of form processing ments to define sections of a page that were to be styled or managed from the form’s definition to the button’s definition. The validation as a group. HTML5 includes new tags that acknowledge the typical invoked by the input element’s new attributes can be suppressed by grouping that developers use in pages: That pages usually have adding the novalidate attribute to a button (useful for buttons that headers, footers and navigation sectors in addition to their primary delete data, for instance). content. The section tag allows you to divide your page into sections, The fieldset element, introduced in HTML 4.0.1, groups arbitrary containing articles (the page’s primary content) and asides (content collections of elements in a form. HTML5 adds three new attributes that isn’t a critical part of the page). to the fieldset: disabled, form (discussed later) and name. The disabled attribute allows you to disable all the elements within a form with a single setting in your code. Listing 1. A Master Page in HTML5. Defi ning Data Structures

While these additions make generating forms more declarative,
A Sample HTML5 Page developers creating LOB applications are most interested in man-
aging data. That’s where Microdata comes in, by providing a way to
organize data within a page into items with properties.
is added, the itemprop attribute defines the properties on the item.
The element to which the itemprop attribute is added provides the value for the property. An optional itemid attribute allows you to
assign a unique identifier for an item.
Written by Peter Vogel This example defines an item called http://phvis.com/customer,
with properties called name and email, and sets those properties to
“Peter Vogel” and “[email protected].” I’ve also used the itemid attribute to assign an id to the item:

VisualStudioMagazine.com · September 2011 · VISUAL STUDIO MAGAZINE 13 COVER STORY HTML5 for ASP.NET Developers

of namespace (much like the itemtypes I’ve used here). Assuming Author:
Peter Vogel
the growth of industry-standard itemtypes, developers will be able Contact: to access data in the client without having to decode a page’s struc-
ture (and create the potential for reusable client-side libraries for The properties that make up an item can be further separated processing specific kinds of data). from the structure of the page by using the itemref attribute with Accessing data in the client is done through extensions to the the itemscope attribute. The itemref allows you to specify the ids of JavaScript API for working with the Document Object Model the elements to be incorporated into the item without embedding (DOM). The new getItems function on the document object allows your item definition in the page’s content. you to retrieve all the items with a particular itemtype (presumably, These tags define the same item as the previous set, but the div a jQuery extension that supports searching on itemtypes will appear element that defines the item is no longer obliged to enclose the soon). Once an item has been retrieved, property values for each elements that specify the item’s properties: item can be retrieved by name using the item’s properties collection.
var itms = document.getItems("http://phvis.com/customer"); for (itm in itms) { Author:
Peter Vogel
alert(itm.properties["email"].content); Contact: The itemtype is the interesting component in Microdata because Flagging Data it supports two kinds of names: ad hoc names that are used only Often, the data displayed on the page may have additional data asso- ciated with it. That additional data may include extra information or provide a way of organizing the displayed data (another role for which developers have used CSS classes). HTML5 provides the data-* Setting up an attributes as a simple way of associating additional information with displayed data. You can add attributes prefixed with “data-” to HTML5 Environment any element and then assign values to those attributes, freeing up the If you want to start playing with HTML5, download the Internet class attribute to do what it was intended to do: control presentation. Explorer Platform Preview (bit.ly/nkUw5q). This is a prototype of This example creates two new data-* attributes, one to hold Internet Explorer 9 with the new Microsoft JavaScript and rendering publisher information and another to hold an internal code: engines. It also has the world’s most minimal UI—there’s not even eliminate some annoying warnings by applying Service Pack 1. In JavaScript, data-* attributes can be retrieved from an element After installing SP1, start Visual Studio, select Extension Manager using the dataset property. This example retrieves the publisher value: from the Tools menu, and also add the Web Standards Update var elm = document.getElementById("PubDate"); from the library. var pub = elm.dataset.publisher; To get Visual Studio to open your site’s pages in Internet The word “can” is probably too strong: as of this writing, no browser Explorer Preview when debugging, right-click any .aspx file and supports the dataset property. However, you can still access the data-* select Browse With. In the resulting dialog, click on the Add button attributes with the old-fashioned setAttribute and getAttribute methods. to display the Add Program dialog, and click on the builder button The data-* attributes will be even more valuable with extensions to (the one with three dots). In that dialog navigate to wherever you jQuery that will select elements based either on the name of the data-* installed the Internet Explorer Preview and double-click on its attribute or on the values assigned to a specific data-* attribute. executable. Back in the Add Browser dialog, enter a friendly name for the browser before clicking the OK button. After returning to Communicating Across Sites and Processes the Browse With dialog, click the Set As Default button. In a service-oriented architecture (SOA) world, the paradigm for But even after all this work, you won’t be able to use all the Web applications changes: While pages are delivered to the browser features discussed in this article. Microdata’s itemref attribute using HTTP requests, each page then engages in a series of conver- and the related JavaScript getItems method aren’t implemented sations with services that retrieve and update data. There’s a catch, in Internet Explorer Preview (at least as of July 2011); the however: JavaScript code in the browser is prohibited from accessing placeholder attribute only works with some of the states of services on any site except the site that the page came from. HTML5 the input element (for instance, when type=“text” but not if Web Messaging (bit.ly/6dratU) provides a mechanism for bypassing type=“number”). Nor are Internet Explorer Preview and Visual that restriction. The site you want to access must, however, create a Studio always in sync. For instance, Visual Studio believes “gateway” page that can be used by other sites. that the command element is an empty element (it’s not) and The first step is to define an iframe in your page to hold a gate- whines if you put text between its open and close tags. Internet way page on the site you want to access. Your second step is to open Explorer Preview, however, does the right thing if you do add the gateway page from the remote site using the window object’s content inside the element. —P.V. open method, targeting the iframe. This example defines a tiny

14 VISUAL STUDIO MAGAZINE · September 2011 · VisualStudioMagazine.com COVER STORY

); Listing 2. Using the postMessage method for data retrieval. window.addEventListener( function messageProcessor(msg) "message", { retrieveData, if(msg.origin == " http://remotesite.com") false ); { $("#custInfo").text = msg.data; function retrieveData (msg) } { } if (msg.origin == "http://localsite.com") { The new WebSockets protocol and related API can be useful var custData; here (once the changes to address the initial security protocols are $.getJSON( addressed), because it supports creating a full duplex connection "Customers/" + msg.data, function (data) that could process on a background thread. { msg.source.postMessage(data, msg.origin); Parallel Process } ); Not all processes finish in seconds—especially those that make } service requests. Web Workers let you run processes in parallel in a } Web browser. To kick off a process, you pass the path to a JavaScript file to a new Worker object: iframe on the page (good for debugging), then opens a gateway var proc = new Worker("Scripts/GetData.js"); page from another site in the iframe: However, the code executing in the Worker has no access to any- thing in the page, including global variables, the elements that