getting directions - 1105 mediapdf.1105media.com/vsmmag/2009/vsm_903dg.pdf · getting...

44
MARCH 2009 Vol. 19, No. 3 GETTING DIRECTIONS .NET developers face adjustments as they start coding for Microsoft’s high-flying collaboration platform. VisualStudioMagazine.com The Art of the Interview ENTERPRISE SOLUTIONS FOR .NET DEVELOPMENT Generate Code from Custom File Formats Create Anonymous Types +

Upload: ngothuan

Post on 22-Apr-2018

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

MA

RCH

20

09

• V

ol. 1

9,

No.

3

GETTING DIRECTIONS.NET developers face adjustmentsas they start coding for Microsoft’shigh-flying collaboration platform.

VisualStudioMagazine.com

The Art of the Interview

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

Generate Code from Custom File Formats

Create Anonymous Types

+

0309vsm.C1.v1 2/19/09 1:55 PM Page 1

Page 2: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

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

Page 3: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

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

Page 4: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

programmersparadise.com800-445-7899

Your best source for software development tools!

Prices subject to change. Not responsible for typographical errors.

programmers.com/theimagingsource

Download a demo today.

BestSeller!

Professional EditionParadise #

T79 02101A01$919.99

®

programmers.com/mindjet

for Windows 1 User

Paradise # F15 17301A02

$299.99

New Release!

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

Unlike the usual linear-based approach of most productivity tools, MindManager 8 uses mind-mapping technology to let you capture, organize, and communicate information using an intuitive visual canvas. You’ll be able to work smarter and transform your ideas into action more quickly.

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

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

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

• Ready-to-use toolbars and dialog boxes

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

programmers.com/telerik

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

Single DeveloperParadise #

TB3 01101A01$615.99

programmers.com/slickedit

SlickEdit 2008 for Windowsby SlickEditSlickEdit 2008 is a cross-platform, multi-lan-guage code editor that gives programmers theability to code in over 40 languages on 7 plat-forms. This latest version builds on the compa-ny’s 20 years of experience in enabling devel-opers and development teams to create, navi-gate, modify, build, and debug code faster andmore accurately.

Paradise # M39 19201A01 $242.99

programmers.com/farpoint

FarPoint Spread for Windows FormsThe Best Grid is a Spreadsheet. Give your usersthe look, feel, and power of Microsoft® Excel®,without needing Excel installed on their machines.Join the professional developers around theworld who consistently turn to FarPoint Spreadto add powerful, extendable spreadsheet solu-tions to their COM, ASP.NET, .NET, BizTalk Serverand SharePoint Server applications.

• World’s #1 selling development spreadsheet • Read/Write native Microsoft Excel Files• Cross-sheet formula referencing• Fully extensible models• Royalty-free, run-time free

Paradise # F02 01101A01 $936.99

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

data search options• file parsers/converters for hit-highlighted

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

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

new .NET Spider API

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

programmers.com/dtsearch

Single ServerParadise #

D29 02101A07 $949.99

New64-bit

Version!

programmers.com/sparxsystems

New Release!

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

Corporate Edition1-4 Users

Paradise # SP6 0001

$182.99

programmers.com/multiedit

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

1-49 UserParadise #

A30 01201A02$161.99

New Release!

programmers.com/lead

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

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

Paradise # L05 03201A01 $2,007.99

programmers.com/pragma

Pragma Fortress SSH—Secure Connectivity by Pragma SystemsPragma Fortress SSH provides a comprehensivesecure connectivity framework for enterprisecustomers.

Full-featured server, graphical clients and graphicalmanagement capabilities are all included.

Pragma Fortress SSH provides:• GSSAPI Kerberos & NTLM authentication• Accelerated SFTP & SCP file transfer• Supports over 1000 sessions• Runs console applications & allows history

scroll back within the same session

Paradise # P35 0439 $550.99

programmers.com/faircom

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

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

including Windows, UNIX, Linux, and Mac OS X

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

Paradise # F01 0131

$711.99

programmers.com/vmware

View PremierParadise #

V55 66101A01

CALLI

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

VDI Included

New Release!

Project5 1/28/09 2:41 PM Page 1

Page 5: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

www.visualstudiomagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 3

COLUMNS

C# CORNER

32 Create Anonymous TypesTaking a careful look at the capabilities the compiler gives to anonymous types provides an excellent tutorial on what you should consider when you create your types—including whether they are classes or structs. BY BILL WAGNER

DEPARTMENTS

6 Editor’s Note BY MICHAEL DESMOND

8 Letters to the Editor

10 First LooksProduct Listings . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

39 Index of Advertisers

40 The Pragmatic DeveloperThe Art of the Interview BY BILLY HOLLIS

FEATURES

12 Getting Directions.NET developers face adjustments as they start coding for Microsoft's high-flying collaboration platform.BY MICHAEL DESMOND

18 Generate Code from Custom File FormatsCreate a custom tool to provide a flexible and easy way to generate code on demand. BY PETER VOGEL

12

“.NET and ASP.NET developers working with SharePoint must

be ready to do things ‘the SharePoint way.’”

Michael Desmond, “Getting Directions” p. 12

COV

ER

CO

MP

OS

ITE

IM

GA

ES

FR

OM

IS

TO

CK

PH

OT

O.C

OM

ContentsMarch 2009 • VOLUME 19 • NO. 3

32

0309vsm_TOC_3-4.v4 2/19/09 11:40 AM Page 3

Page 6: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com4

LEARN FROM THE PROSAs a developer you are constantly facing theproblem of how to keep up with all the newtechnologies being released while still get-ting your job done. You keep hearing aboutsolutions to your programming problems butthe question is: are they the right solutionsfor your particular needs? You could spendhours or even days trying to find theanswers yourself, or you could let theexperts do it for you. Redmond Media GroupEvents offers a variety of conferences andshows where you can learn about new tech-

nologies and what they might offer you, attend in-depth workshops thatfocus on topics specific to your needs, ask questions of the experts, andinteract with your peers to discuss problems they face and what solutionsthey’ve come up with. Whether it’s Web design, .NET development, or SQLServer programming, we’ve got an event that matches your needs. VisitRedmondEvents.com to learn more about upcoming conferences and shows.

ONLINE ARTICLES

Practical ASP.NET: Accessing Connection Strings ReliablyIn his ongoing series on ASP.NET, Peter Vogel provides an alternative tothe default mechanism for accessing connection string—and plugs hisnext book. LOCATOR+ CODE: VS0903PV1

Practical ASP.NET: Updating Multiple GridView RowsPeter Vogel explains how putting updateable controls in theItemTemplate in a GridView gives developers what they want: the abilityfor users to change more than one row at a time. The cost is writingsome extra code. LOCATOR+ CODE: VS0903PV2

ONLINE TUTORIALS

Classic VB Corner: Let Me Tell Ya Where to Stick ItIn these days of increasingly common least-privileged users, whereshould you store your application data? Karl E. Peterson drills down onthe best approaches to organizing and accessing your system folders.LOCATOR+ CODE: VS0903KP1

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

VisualStudioMagazine.com

ContentClassic VB Corner: Forward CompatibilityDoes anyone really expect to be able to take data fromthe current version of AppX and use it freely in the previous version of AppX? Of course not! Karl E. Petersondiscusses forward compatibility and how data assetssimply must move forward from one version of an application to the next. LOCATOR+ CODE: VS0903KP2

GIVE US YOUR FEEDBACKWe at Visual Studio Magazine and VisualStudioMagazine.comare constantly trying to improve the content we provide youand the way that content is presented, both in the pages ofthe magazine and online. We value your opinions about anyaspect of the magazine or our Web site. If you have anycomments, criticisms, or suggestions on how we mightimprove things please feel free to contact us. You can reachus by email at [email protected] or go online atVisualStudioMagazine.com and post your comments.

What Are Locator+ Codes?Locator+ codes give you instant access to a feature on VisualStudio Magazine Online. Simply type the Locator+ code intothe field in the upper-right corner and click on FIND IT.

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

VirtualizationReview.com1105 Media recently launched a new Web site devoted exclusively to covering all aspects of IT virtualization.VirtualizationReview.com helps you harness the power ofvirtualization by delivering news and in-depth coverage ofthe products, vendors, issues, and technologies transform-ing IT through virtualization. The site also features articles,tips, and timely information about all aspects of virtualiza-tion including servers, storage, desktops, applications, andmore. Visit VirtualizationReview.com now to start yourmove to a more efficient, powerful virtual environment.

0309vsm_TOC_3-4.v4 2/19/09 11:41 AM Page 4

Page 7: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Integrate Mapping and GIS into Your Applications

Give your users an effective way to visualize and analyze their data so they can make more informed

decisions and solve business problems.

By subscribing to the ESRI® Developer Network (EDNSM), you have access to the complete ESRI

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

every platform. Whether 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.

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

Subscribe to EDN and leverage the power of GIS to get

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

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

Page 8: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Editor’s Note

BY MICHAEL DESMONDeditor in chief

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com6

By now you’ve no doubt noticed some changes in this month’s issue of Visual Studio Magazine.

There’s a lot going on at VSM as we work to improve the pub-lication, and we’re anxious to let you know what we’re up to,and to hear your opinions about what we might do better.

It’s probably best if I start at the top. Back in January ourparent company, 1105 Media Inc., announced that it wasmerging its two developer publications—VSM and the twice-monthly Redmond Developer News—into a single, integratedpublication under the title Visual Studio Magazine. The moveblends the best aspects of each magazine, combining VSM’sdetailed how-to content and coding tutorials and RDN’s in-depth analysis of key issues and technologies.

In a sense, RDN and VSM have been two sides of thesame coin. RDN gave developers fair warning of what wascoming, be it new technologies or newly discovered chal-lenges, and VSM showed them how to work with it.

Now these two missions are being united under the VSMbanner. The move reflects the fact that developers need con-text. They need to know about the tools they’re mastering, sothey can make better decisions on how to use them. To thatend, future issues of VSM will deliver the kind of in-depthfeatures, timely technology and product news, plus expertinsight that you’ve seen in RDN since 2006.

The transition brings significant changes to the VSMstaff. I want to take a moment to recognize the outstandingefforts of former VSM Editor in Chief Patrick Meader andManaging Editor Guy Wright, who are both moving on fromVSM as part of the transition. I’ve worked on occasion withPatrick over the past two years, and I’ve respected him deeplyfor his intelligence, composure and commitment to princi-ple. Patrick is as dedicated and forthright a person as I’ve everrun across in my 16 years in IT publishing, and his successover the years at VSM is testament to that.

Joining the VSM team are three new faces. KathleenRichards is the new executive editor and will guide many ofthe key how-to departments and features at the magazine.Richards was senior editor at RDN and before that at Appli-cation Development Trends magazine. Jeffrey Schwartzarrives as news editor, where he’ll drive the front-of-the-booknews and review content. Schwartz comes to VSM from RDN,where he managed the book’s large news section. Prior to thathe was a senior editor at VAR Business.

As for myself, I’ve moved over as editor in chief of RDNto serve as editor in chief of VSM.

What does it all mean? Quite a lot, actually. The new staffreflects an expanding mission for VSM. The magazine willcontinue to publish cutting-edge tutorial and how-to con-tent, but our coverage will expand to include issue-orientedfeatures, timely news analysis and incisive commentary.Developers working with tooling as expansive and as power-ful as Visual Studio don’t work in a vacuum, and Visual StudioMagazine will reflect that.

This issue is really the first step in the effort to broadenthe scope and reach of VSM. In April, we plan to unveil a redesigned publication that is fully aligned with ourexpanded vision.

I want to emphasize that Visual Studio Magazine is hereto serve you.With so many big and exciting changes afoot,we’re more anxious than ever to hear the opinions and inputof developers and managers.What can we do to improveVSM? What kinds of stories, content, tutorials and interac-tion are you looking for? And how can these things be tunedto help you do your jobs better? We want to hear your ideas—e-mail me at [email protected].

PH

OT

O B

Y IR

A W

YM

AN

WHAT HAPPENS NEXT

0309vsm_EdNote_6-8.v2 2/19/09 3:25 PM Page 6

Page 9: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

WinForms • WPF • ASP.NET • Silverlight • iPhone • Mobile • ActiveX

Grids • Charting • Reporting • Scheduling • Menus and Toolbars • Ribbon • Data Input • Editors • PDF

STUDIO FOR SILVERLIGHTSTOCK PORTFOLIO DEMO STUDIO FOR IPHONE

CTP NOW AVAILABLE

Studio for SilverlightProduce limitless RIAs: state-of-the-art Silverlight controls

• Find the Silverlight 2 control you need to build rich data apps:largest selection of Silverlight controls including uniquecontrols like animated GIFs, spell-checking, file uploader,and more

• Increase functionality with a small footprint: averagecontrol size of 77KB (XAP size) eliminates the need to worryabout adding to the size of the download

• Access the best resources: 15+ samples with source codefor quick learning

Studio for ASP.NETAJAX-enabled controls for desktop-like experience on the Web

• Build lightweight, high-performance Web apps: 3xsmaller footprint, 10x faster performance

• Style and animate your Web UI without coding: dozensof built-in visual styles & animation effects

Studio for iPhoneBuild Web apps that look and feel like the native UI of the iPhone and iPod touch

• Develop without the hassle of learning a new technology:Studio for iPhone controls are built on the familiarASP.NET Framework

Studio Enterprise 2008 v3 deliversexactly what you need to producenext-generation UIs for the Web.

www.componentone.com/amazingwebGET STARTED TODAY DOWNLOAD YOUR FREE TRIAL at

ComponentOne Sales 1.800.858.2739 or 1.412.681.4343© 1987-2009 ComponentOne. All rights reserved. iPhone and iPod are trademarks of Apple Inc. Allproduct and brand names are trademarks and/or registered trademarks of their respective holders.

Visit Us at VSLive! Febuary 23rd-25th at booth #328-330

Project7 2/10/09 3:39 PM Page 1

Page 10: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com8

Letters to Visual Studio Magazine are welcome. Letters must include yourname, address and daytime phonenumber to be considered for publica-tion. Letters might be edited for form,fit and style. Letters express the viewsof the individual authors, and do notnecessarily reflect the views of theeditors, VSM or 1105 Media. Pleasesend them to Letters to the Editor, c/oVSM, 16261 Laguna Canyon RoadSte. 130 Irvine, Calif. 92618; faxthem to 949-265-1528; or e-mailthem to [email protected].

Letters

Agile Arguments

Billy Hollis’ The Pragmatic Developer column (“Is Agile Rock or Disco?” January2009) brings an interesting point to light: Will Agile survive the times?

However, I think the author missed a different, critical point: Agile is a mindset and nota process. Truly Agile development is adaptable, and therefore it can work with non-seasoned developers.

Ted Malone,Colorado Springs, Colo.

I’d like to further a point Hollis made in his article: It’s hard to do any development withoutgood developers. Instead of trying to figure out how to make do with not-so-good developers,we need to figure out how to turn those with potential into good developers, and how toencourage the rest to find a more suitable field in which to work.

The so-called “software crisis”—a shortage of good developers compared to the amountof software that needs to be written—is an issue of supply and demand. There’s an inherentundersupply of good developers, but there’s also an oversupply of demand as many clientsjust want variations on the same thing. If it’s more profitable to be a good developer, thosegood developers will also create frameworks and tools to help address the demand-side prob-lems as well.

Anonymous,Posted online

WF: Change for the Worse?

I suppose out of all the possible changes that might trouble me in Windows WorkflowFoundation (WF) 4.0—as discussed by Kathleen Dollard in her Ask Kathleen column(“Windows Workflow Changes Direction,” January 2009)—the loss of the code activity is themost upsetting. This makes the possibility of making “lightweight” WF activities that accom-plish relatively simple tasks more difficult than necessary. By removing this piece of function-ality, Microsoft has effectively shackled the developer to creating activity libraries. While thathas its place, this seems like the pendulum swinging way too far in the other direction.

And frankly, I disagree with Dollard that moving completely to declarative creation ofworkflows is a good thing. Performance improvements are great, but performance improve-ments that cause the loss of very useful functionality are just wrong.

Marcelo Lopez, Jr.,Florida

VisualStudioMagazine.comMarch 2009 • Volume 19 • No. 3

Editorial StaffVice President, Doug Barney

Editorial DirectorEditor in Chief Michael Desmond

Executive Editor Kathleen Richards

News Editor Jeffrey Schwartz

Managing Editor Wendy Gonchar

Associate Managing Editor Katrina Carrasco

Contributing Editors

Andrew J. Brust, Ken Cox, John Cronan, Dan Fergus, John Gavilan, Roger Jennings, Don Kiely,

Martin Kulov, Jeff Levinson, Bill McCarthy, John Charles Olamendy Turruellas, Keith Pleas,

Peter Varhol, Bill Wagner

Art Staff

Creative Director Scott Shultz

Graphic Designer Erin Horlacher

Online/Digital MediaEditor, VisualStudio Becky Nagel

Magazine.comExecutive Editor, New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor, Web Gladys Rama

Web Producer Shane Lee

Director, Web Development Rita Zurcher

President Henry Allain

Vice President, Publishing Matt N. Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S. Cook

President & Neal VitaleChief Executive Officer

Senior Vice President Richard Vitale& Chief Financial Officer

Executive Vice President Michael J. Valenti

President, 1105 Events Dick Blouin

Vice President, Finance Christopher M. Coates& Administration

Vice President, Digital Media, Abraham M. LangerAudience Development

Vice President, Information Erik A. LindgrenTechnology & Web OperationsVice President, Digital Media, Doug Mashkuri

AdvertisingVice President, Carmel McDonagh

Attendee Marketing

Chairman of the Board Jeffrey S. Klein

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

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

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

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

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

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

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

0309vsm_Letters_8.v3 2/19/09 2:47 PM Page 8

Page 11: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

For maximum efficiency, follow our

three profiling tips outlined below.

1. Profile your .NET codeA code profiler is an essential

tool to have in your development

toolkit. Although manual logging

can sometimes help, it is often

impossible to fi nd performance

bottlenecks without a code profi ler.

A profiling tool takes the guesswork

out of performance analysis and

drastically reduces the amount of

time taken to find problem code.

2. Quickly locate yourperformance bottleneckRun ANTS Profiler Pro to obtain

detailed quantitative data that will

help you identify ineffi cient resource

usage. ANTS Profiler gives you hit

count and line-level timings, so you

can quickly identify the specifi c

lines of code which are affecting the

performance of your application.

No time wasting. No guessing.

Use real data instead!

3. Optimize effi cientlyNow that you know exactly where

to focus your performance-boosting

work, you can start optimizing your

code effectively. Optimize your code

only where it needs to be improved,

and don't try to make unnecessary

changes that will not solve your

performance problem.

How to boost the performance of your.NET applications with ANTS Profiler™Performance is crucial, so here are some tips to make sure

that your applications run effi ciently.

Download your 14-day, fully functionalfree trial from www.red-gate.com

ANTS Profiler shows you line-level timings, so you can drill down to the specific lines of code responsible for performance ineffi ciencies.

Select a region on the timeline and get the performance data just for that region.

"We were able to improveperformance in parts of

the application up to 10 times,and our customer noticed theresults. A powerful, instantlyunderstandable profi ler.Highly recommended."Dan Ports Lead Developer, Intrigma Inc

"ANTS Profi ler took usstraight to the specifi c areasof our code which were thecause of our performanceissues."Terry Phillips Sr. Developer,

Harley-Davidson Dealer Systems

Project2 2/11/09 11:06 AM Page 1

Page 12: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

LooksFirst

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com10

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

CCoverity PreventCoverity Inc. has improved the support for man-aged and native code in its static-analysis soft-ware. With Coverity Prevent, developers canautomatically scan and analyze C#, C, C++ andJava source code on their desktops or on thebuild server. It’s one of the few static-analysistools that supports both Visual Studio andEclipse integrated dev environments.

The product ships with a Web server, whichconnects to the help desk or Active Directoryserver on your network and a back-end data-base. Developers open the Coverity browserand log on to the Web service. Prevent buildsthe source code, analyzes it based on selectedquality and concurrency checkers, and thencommits the results to the database. A build-utility wrapper wraps around the build butdoesn’t change it. Depending on the number ofcheckers, the build and analysis typically takethree to five times the normal build time.

After a run, developers can view a break-down of the code base in the browser: howmany files and lines of code, the number of newdefects since the last Run ID, and outstandingdefects that still need to be inspected and clas-sified. Developers can’t edit the code from with-in the Prevent interface, however.

The latest version beefs up VS integration,enabling developers to perform static analy-sis from within VS 2005 and VS 2008. Thecompany has also added support for WindowsVista, Windows Mobile, Windows Automotiveand Xbox.

In addition, Coverity has extended Pre-vent’s C# functionality with new quality andconcurrency checkers. Prevent is the firstproduct to support C# concurrency testing forissues such as deadlocks and race conditions,according to the company. With this upgrade,

Coverity Prevent and Quince UX Patterns Explorer

it also now offers concurrency modeling tohelp developers find critical defects in multi-threaded Win32 apps.

Prevent is the flagship product in Coverity’sSoftware Integrity Suite, and the only productthat currently supports C#. Upcoming static-analysis tooling will take advantage ofMicrosoft’s efforts to put annotations into itssystem header files.

Coverity Prevent

Coverity Inc.

Price: Contact vendor for pricing

Web: www.coverity.com

Phone: 800-873-8193;

415-321-5237

Quince UX Patterns ExplorerComponents vendor InfragisticsInc. has launched a unique Sil-verlight 2 application called“Quince” UX Patterns Explorer.The app offers developers aresource for best practices inuser experience design and user interface patterns. With Quince, developers can honetheir UI design skills with guidance from thecommunity-driven catalog by seeing what pat-terns other practitioners have used and byviewing developer feedback. Developers canalso share and upload their own UI patterns.

Quince offers guidance on common patternsfor complex data entry, label alignment andnavigation, among other UI tasks. The library isinitially based on tools and practices that the20-year-old company uses internally, as wellas expertise garnered from industry sources.

Quince aggregates close to 100 patternsand shows implementations via a carousel

format on various platforms, includingASP.NET, Windows Forms and PHP. Develop-ers can search Quince for commonly used pat-terns based on end user tasks, wireframe maplocations and tags. The patterns catalog is setup so that the community can comment onpatterns and their experiences in real time.The patterns are aggregated based on com-munity feedback.

Yahoo! Inc. and Google Inc. offer patternlibraries, but there isn’t a de facto resource inthe .NET and Microsoft space .

Quince

Infragistics Inc.

Price: No fees; registration required

Web: www.community.infragistics.com/ux

Phone: 888-448-0097; 609-448-2000

Editor’s Note: Please send product information

to New Products Editor, c/o VSM, 16261 Laguna

Canyon Road, Ste. 130, Irvine, CA 92618;

Phone: 949-265-1565, fax: 949-265-1528;

e-mail: [email protected].

0309vsm_FirstLooks_8-9.v5 2/19/09 12:18 PM Page 10

Page 13: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

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

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 11

IIf you handle enterprise-level business intelli-gence (BI) and financial reporting, it won’t be longbefore the front office summons you to deal witheXtensible Business Reporting Language (XBRL).XBRL is an XML vocabulary for exchanging busi-ness and financial data. It’s a standard formachine-to-machine reporting that’s been adopt-ed by the U.S. Securities and Exchange Commis-sion (SEC) and European authorities.

Altova, well known for its leadership in allthings XML, has updated its products to supportXBRL and bundled them into MissionKit 2009 forEnterprise Software Architects. The goal is to giveyou the tools (but not necessarily the training) todeliver reports compliant with the InternationalFinancial Reporting Standards (IFRS).

For XBRL beginners, it would have been ideal tohave a hands-on walkthrough that starts with afinancial database and ends with a valid XBRL doc-ument ready for submission to authorities. Alas,there’s no “XBRL For Dummies” manual included.While each application includes tantalizing tidbitson working with XBRL, I felt like I was solving a jig-saw puzzle without seeing the entire picture first.

XBRL is the “buzz” in Altova’s all-in-one suite, but don’t over-look the features that have long made the individual compo-nents the premier development environment in the XML space.It’s hard to beat XML Spy as an all-round markup editor, validatorand XPath query designer. Its Grid view is especially useful forcollapsing and exploring very large documents. As you work, theMessages pane reports errors, explains the problem and high-

lights the location. The other day, I fed XML Spy an XML file con-taining Expression Encoder ScriptCommands. XML Spy generat-ed a schema for it in an instant. Be careful what you ask for whenconverting an entire database into XML, though. I ended up with234 files while searching in vain for XML Spy’s cancel button.

MapForce is Altova’s flexible tool for mapping and filteringdata graphically from one source to another. The source or tar-get can be a database, .EDI document, Web service, Excel 2007spreadsheet or a lowly .CSV file. MapForce will generate the C#classes you might need to automate data conversions.

The third major component, StyleVision, lets you design XLSTtemplates into which you pour data for human consumption. Ifyou’re getting into XBRL, be sure to explore the quarterly reportsample and the Word 2007 preview to see the richness of itsoutput.

One issue I encountered with MissionKit 2009 was preview-ing a stylesheet as a PDF. Even though I had chosen a full instal-lation, StyleVision strangely prompted me for a 19MB downloadof the Apache (Java) Formatting Objects processor. Even withthat in place, the PDF document still failed to appear. I wouldexpect Altova’s setup kit to automatically install the renderingengine and tell its PDF module where to find it. VSM

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

“ASP.NET 3.5 for Dummies” (Wiley).

Altova MissionKit Boasts XBRL Savvy

PRODUCE READABLE FINANCIAL DOCUMENTS USING XSLTSTYLESHEETS. StyleVision, a member of Altova’s MissionKit 2009suite, lets you design human-readable documents from machine-to-machine files in XBRL format. The output options include HTML, RTF,PDF and Word 2007.

AT A GLANCE

MissionKit 2009 for Enterprise Software ArchitectsAltovaWeb: www.altova.comPhone: 978-816-1600Price: $1,739Quick Facts: Integrated bundle of XML, database, XSLTdesigner, validation, and publishing tools with addedemphasis on financial reporting support.Pros: Handles all popular and emerging XML-basedtechnologies including the XBRL-compliance standard;extensive online documentation and Web-based support; many examples.Cons: Needs end-to-end walkthrough on producingXBRL reports; rendering engine for previewing PDFdocuments not fully installed.

0309vsm_FirstLooks_8-9.v5 2/19/09 12:18 PM Page 11

Page 14: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

S H A R E P O I N T

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com12

COM

PO

SIT

E IM

AG

ES

FR

OM

IST

OC

KP

HO

TO

.CO

M

F E AT U R E

.NET developers face adjustments as they start coding forMicrosoft’s high-flying workflow and collaboration platformBY MICHAEL DESMOND

Getting Directions

0309vsm_F1Sharepoint_12-17.v7 2/19/09 4:35 PM Page 12

Page 15: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

13

S H A R E P O I N T

Behind the activity is the wildfire growth of Microsoft’s file sharing, collaboration and portal platform, which includes Microsoft OfficeSharePoint Server (MOSS) 2007 and WindowsSharePoint Services (WSS) 3.0 integrated intoWindows Server.Last year, the SharePoint businessunit surpassed 100 million licenses and $1 billionin total revenue, according to Microsoft. Noworganizations are looking to leverage those invest-ments by adding custom functionality and applica-tions to their SharePoint infrastructure.

That trend is producing its share of growingpains, as .NET dev shops contend with Share-Point’s unique demands and uneven tooling. AtMicrosoft’s Tech·Ed Conference in June 2008,Chairman Bill Gates admitted during his keynoteQ&A that the company had been caught flat-footed by the amount of development activityaround SharePoint.At the time, he said Microsoftwas working to make SharePoint developers first-class citizens.

Since then, Microsoft has released the freeVisual Studio 2008 extensions for SharePoint,which provides Visual Studio project templates forbuilding, debugging and deploying SharePointprojects and applications.The January communitytechnology preview (CTP) of Visual Studio 2008Extensions for Windows SharePoint Services 1.3adds 64-bit support, refactoring support forrenaming Web parts, and a command-line inter-face for enabling continuous integration and build.The final version is likely due in April, says PaulAndrew,Microsoft technical product manager forthe SharePoint Developer Platform.

“Microsoft has been scaling up our guidance,and our application and tools, really, really fast,”Andrew says, noting that Visual Studio 2010 willfully integrate SharePoint development support.

Making the TransitionEvidence of the effort to scale up guidance is evident in Web sites like Microsoft’s SharePointDeveloper portal (http://tinyurl .com/bsx8k9)and the MSDN-hosted SharePoint Server (http://

tinyurl.com/67e7gk) and Windows SharePointServices (http:// tinyurl.com/7typk6) DeveloperCenters. The sites offer step-by-step tutorials,design patterns, best practices and otherresources for developers working with the platform.

Still, challenges remain.Veteran SharePointdevelopers complain that a lot of critical insightand guidance remains scattered among dozens ofindividual blogs and SharePoint-themed sites.

“My Google reader is filled with stuff I needto check on, but it’s all scattershot,” says Ruther-ford Wilson, director of product management forAtalasoft Inc., an ISV that in February releasedVizit SP, an image-viewing application for MOSSand WSS environments.“There are books, blogs,and that’s about it.”

Ryan Thomas, director of the SharePointpractice at consultancy Syrinx Consulting Corp.,says developers new to SharePoint are best servedby simply wading into the environment.

“The first thing I would do is build a Webpart. Build and have ‘Hello World’ working in 30minutes. Then download the SDK and the objectmodel. If you’re going to be a developer, under-stand the object model and learn how to writecode,”he says.

Thomas advises developers to visit theMicrosoft CodePlex site to examine open sourceSharePoint projects similar to their own.

He warns that seasoned .NET developersmay find the dynamics around SharePoint devel-opment to be quite different from traditional.NET development. He says SharePoint projectstend to be client-facing, involving frequent andintense interaction with business stakeholders.There’s a good deal of expectation setting thatmust be addressed, in part because these users areoften familiar enough with SharePoint to expectquick results.

“VPs, CIOs, business people—they justdon’t understand the concept of,‘three weeks andcome back with code,’” Thomas says. “It’s veryimportant to talk to them.”

T imes are tough all over,but it seems somebody forgot to tell that tothe growing ranks of SharePoint developers. Even as general ITand development budgets turn south, industry watchers say

the amount of activity around SharePoint applications and featurescontinues to rise.

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 13

0309vsm_F1Sharepoint_12-17.v7 2/19/09 4:35 PM Page 13

Page 16: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

S H A R E P O I N T

Tale of the ToolsOne of the enduring complaints about SharePoint development has centered aroundtooling. That situation is now changing,thanks in large part to the release of the VisualStudio extensions for SharePoint and usefulutilities like the SPDisposeCheck tool forreleasing unused memory. Still, major gapsremain in the SharePoint developer chain.

“The extensions are weak, in my opin-ion,” writes Spencer Harbar, a U.K.-basedindependent SharePoint developer and frequent speaker at Microsoft conferences,in an e-mail interview. “At best the exten-sions are a Band-Aid to bridge the gapbetween where we are now, and the future ofSharePoint dev tools.”

Harbar says the extensions fall shortfor enterprise development, which canexpose weaknesses and flaws in the tooling.He adds that the integrated SharePoint tool-ing in Visual Studio 2010 (VS10) should bemuch better. “I cannot speak much to theVS10 tools without breaking NDAs, but Ihave complete confidence that they willoffer a huge step change in terms of devel-oper tools for SharePoint,”he says.

Another issue is the fact that Share-Point environments must run on WindowsServer—a nagging issue for developers whoprefer to code on their Windows XP or Vistaworkstations. Microsoft’s Andrew saysdevelopers today have two choices: Eitherrun Visual Studio on the same WindowsServer OS that hosts SharePoint, or stand upa virtual machine that incorporates Win-dows Server and the target SharePoint envi-ronment. Most shops, he says, opt for thelatter solution.

Leading component maker Compo-nentOne LLC is among them. The companyin January released CTP versions of itsSharePoint Web Parts line, which includemap, chart and datagrid controls for Share-Point environments.

“You need to make sure you have accessto a testing environment that is not yourdevelopment machines, that’s particularlyimportant for SharePoint,” says Dan Beall,product manager for ComponentOne.“Sometimes you have to use remote debug-ging. It’s not as fluid as debugging on a targetmachine,but one thing you can do is you canhave your code write entries to SharePoint log

THE SHAREPOINT TOOLBOX

SharePoint provides an enormous amount offunctionality but can be challenging for newdevelopers trying to deploy solutions to a

server. Fortunately, there are several free Microsoftand third-party tools that can be used to create Web parts, site definitions, eventreceivers and more. Here’s a quick rundown of a few timesaving tools that can significantly increase your productivity when building SharePoint applications.

WSPBuilderWSPBuilder provides a nice way to build manifest.xml, .DDF and .WSP solution filesquickly and easily from the command line or through a Visual Studio add-in. It traverses a “12” folder structure in VS and generates the appropriate files needed todeploy a solution. It can be downloaded from www.codeplex.com/wspbuilder.

STSDevSTSDev can be used to build different SharePoint components such as Web parts andfeatures more easily. Once a project type is selected (note that C# is currently theonly supported language), it will create a VS 2005 or 2008 project automaticallywith the necessary SharePoint files and folder structure. STSDev can be down-loaded from www.codeplex.com/STSDev.

CAML Query BuilderCollaborative Application Markup Language (CAML) can be challenging to build fromscratch. Fortunately, U2U has released a free tool called CAML Query Builder that canbe used to build CAML queries visually without having to know a lot about CAML. Itwill output the proper CAML syntax for use with objects such as SPSiteDataQuery.CAML Query Builder can be downloaded from http://tinyurl.com/9f5ulo.

Business Data Catalog Definition EditorThe Business Data Catalog (BDC) allows external data to be integrated into Share-Point that can be bound to built-in MOSS Web Parts or custom controls. To use BDCfunctionality you create custom .XML metadata files that define connection informa-tion, queries to execute, plus much more. Although the tool isn’t as flexible to workwith as some of the other tools out there, the price can’t be beat. It’s part of Share-Point 2007’s SDK 1.2 release. Read more about it at http://tinyurl.com/cpot8a.

Visual Studio Extensions for SharePointMicrosoft has released extensions for VS 2005 and 2008 that can simplify theprocess of building and deploying List items, Web Parts, Site Definitions and more. Atpress time version 1.3 for VS 2008 was released as a community technology pre-view. Additional information can be found at http://tinyurl.com/9qo9s8.

SPDisposeCheckUnwary SharePoint developers can easily run into a situation where COM-basedmemory doesn’t get released by CLR garbage collection. The resulting memory leak-age can cripple performance and cause unexpected crashes and failures. TheMicrosoft SharePoint Dispose Checker Tool, known as SPDisposeCheck, analyzescustom compiled assemblies so developers can ensure proper disposal of unusedresources. Check it out here: http://tinyurl.com/dhn69w.

—Dan Wahlin

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com14

0309vsm_F1Sharepoint_12-17.v7 2/19/09 4:35 PM Page 14

Page 17: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Project2 2/17/09 3:16 PM Page 1

Page 18: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

S H A R E P O I N T

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com16

files. There are a couple of freeware tools for looking at what’s in thelog files.”

SharePoint developers have come to rely on a growing collectionof freely available tools and utilities to help them address the extendedtool chain. Microsoft utilities, like the SPDisposeCheck tool, helpstamp out troubling memory leakage conditions that can occur withunmanaged component code, while the CAML Query Builder easesthe learning curve around SharePoint’s Collaborative ApplicationMarkup Language (CAML).The result: Many dev shops have assem-bled ad hoc tool chains to address the unique demands of SharePointcoding.(See “The SharePoint Toolbox,”p.14.)

‘The SharePoint Way’Ultimately, .NET developers face a subtle challenge in adjusting to life with SharePoint. .NET and ASP.NET developers workingwith SharePoint must be ready to do things “the SharePoint way,”

says Anne Thomas Manes, vice president and research director atBurton Group.

“SharePoint presupposes a bunch of design patterns and youkind of have to build your application around those design pat-terns,” she says. “And if you want your own design pattern, it’sprobably not worth the time and effort. Don’t attempt to force fit other design patterns into it, because it will just be a very frus-trating experience.”

Andrew draws a parallel with ASP.NET programming proj-ects, where developers typically start off by building a framework toaddress administration, security, data access and other issues.SharePoint, he says, essentially acts as the framework.

“That has the advantage that if you take a SharePoint develop-er, they already know that framework, they don’t have to learn anew framework,”he says.

The problem is that the SharePoint framework is so large that

“There’s a lot of features in WSS that Microsoft doesn’t really advertise to the rest of the world.”

Anne Thomas Manes, Vice President and Research Director, Burton Group

0309vsm_F1Sharepoint_12-17.v7 2/19/09 4:35 PM Page 16

Page 19: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

S H A R E P O I N T

developers often create custom code for features that are alreadythere. Harbar urges developers to look carefully before concludingthat a custom Web part or application is necessary.

“Easily the most common mistake is not having a core under-standing of the product architecture and therefore choosing thewrong approach to meet specific business requirements.SharePoint issuch a huge platform that it’s incredibly easy to start implementingcustom code for a task that SharePoint does,”Harbar writes.

He adds that developers often make the mistake of assumingthat SharePoint is “just .NET,”when in fact .NET developers face asignificant ramp in mastering SharePoint dev projects.

Even within the SharePoint family there are choices to bemade. Manes says that many enterprises today opt to develop forSharePoint Server, when they could achieve similar results andenjoy a more manageable environment by deploying logic to Windows SharePoint Services (WSS) instead. She says organiza-tions often conclude—wrongly—that WSS lacks the features theyneed to support workflow, coordination, scheduling and othercommon business processes.

“There are a lot of features in WSS that Microsoft doesn’treally advertise to the rest of the world,” Manes says. “I can use aJava portlet and have that be the interface into WSS, because that

works through the Web services interface as opposed to the .NETinterface.”

Ultimately, Microsoft’s Andrew says that .NET developersmust learn to unlearn some of their old assumptions when movingto SharePoint.

“One of issues is people taking the approach—and this happensbecause projects need to be done fast—that their .NET experiencewill get them through their SharePoint project,”Andrew says.“Theydo have to learn new skills.” VSM

Michael Desmond ([email protected]) is editor in chief ofVisual Studio Magazine.

GO ONLINE

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

READ

VS0903MD Read this article online, which includes more information about how SharePoint adoption is raising data-management concerns; plus a Q&Awith SharePoint development trainer and VSM online columnist Dan Wahlin.

PERFECTION IN SOFTWARE PROTECTION

Exceptional Software Protection

CodeMeter for .NET

Order your Free Software Development Kit now!Phone 1-800-6-GO-WIBU | [email protected]

Access Protection

Document Protection

Software Protection

Media Protection

More than 1000 Key-Storage License Entries�

- Different ISV´s can share one dongleSecure Expiration Date with a Real-Time-Clock�

- Unique Time Certifi cation Feature- Control Relative and/or Absolute timeMore ways to sell = More sales�

Create Student and Version Licenses�

Control Network Licensing�

- Control concurrent users- Control “roaming“ usersCreate “Standby“ Licenses�

- Hot Standby and Cold Standby- Provide Overfl ow Licenses

Pay-Per-Use Counter�

etwork Licensing

WIBU-SYSTEMS USA Inc.110 W Dayton Street,Edmonds, WA 98020United [email protected]

PERFECTION IN SOFTWARE PROTECTION

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 17

0309vsm_F1Sharepoint_12-17.v7 2/19/09 4:35 PM Page 17

Page 20: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

B U I L D I N G C U S T O M T O O L S

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com18

You’re already using a custom tool everytime you add a dataset to an application. VS setsthe CustomTool property of the dataset’s .XSD toMSDataSetGenerator. Whenever you close the.XSD file—or, in Visual Studio 2008 (VS 2008),whenever you switch away from the file—VSpasses MSDataSetGenerator the contents of the.XSD file, which MSDataSetGenerator then con-verts to code for the .XSD’s code file and handsback to Visual Studio.

You can design your own input format andwrite your own custom tool to generate code foryou. Once you build your custom tool, you simplyhave to enter its name in the CustomTool property

of the file with your input. VS takes care of therest (see Figure 1, opposite page).

Using a tool to generate repetitive codeensures consistency and reliability. It guaranteesthat your code generates the same way everytime, reducing the amount of testing you have todo. Using a custom tool can also make you moreproductive, provided that entering the specifica-tions is faster than writing the code. If you decideyou need to enhance your generated code, justmodify your custom tool to incorporate yourinsights.Your class will be regenerated automati-cally with the new version of the code the nexttime you build your project.

Y ou’re writing the same code over and over again with onlyminor changes, and you’re about to do it again. Stop. If you’recreating a standalone class (either a class that you’ll call from

your application’s code or a class that you can inherit from),build a customtool that writes the code for you now and every time you’ll need it.

ILLU

ST

RA

TIO

N F

RO

M IS

TO

CK

PH

OT

O.C

OM

TECHNOLOGY TOOLBOX

F E AT U R E

Create a custom tool to provide a flexible and easy way to generate code on demand. BY PETER VOGEL

Generate Codefrom Custom File Formats

VB.NET

C#

SQL Server

ASP.NET

XML

Other:

0309vsm_F2HowTo_16-23.v7 2/19/09 12:33 PM Page 18

Page 21: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

B U I L D I N G C U S T O M T O O L S

Installing to the GAC AutomaticallyCreating a custom tool (also called a “single file generator”) pres-ents one problem.VS is a Windows application that calls a customtool directly, so your custom tool must integrate with Windows andCOM.You can create your custom tool in .NET, but you must makeyour tool available from Windows.

To enable VS to call your tool,you must register it with Windows,add at least one registry key to let VS know your custom tool exists,and install your tool in the Global Assembly Cache (GAC). Thismeans you must give your DLL a strong name. The good news isthat you can configure VS so that all of these operations happenevery time you compile your application. More good news: Most ofthe support for creating a custom tool is boilerplate and is identicalfrom one custom tool to another.You only have to write it once andthen copy and paste it to any other tool you create.

You can build a custom tool in a variety of ways. I use theMicrosoft.VisualStudio.Shell.Interop.IVsSingleFileGenerator andMicrosoft.VisualStudio.OLE.Interop.IObjectWithSite interfaces.Tocreate a custom tool,begin by creating a class library in the language ofyour choice and then add to it references to the Microsoft.VisualStu-dio.OLE.Interop and Microsoft.VisualStudio.Shell.Interop libraries.

Next, configure your project to have VS call the gacutil utility toput your DLL in the GAC after your application compiles. First, findthe full path to wherever gacutil.exe is installed on your computer. InVS,open the Project Properties for your application.If you’re workingin Visual Basic, select the Compile tab and click on the Build Eventsbutton. If you’re working in C#, simply select the Build Events tab.Add these lines to the PostBuild event textbox (replace <full path togacutil> with the path to your copy of gacutil.exe):

"<full path to gacutil>\gacutil.exe" -u "$(TargetName)""<full path to gacutil>\gacutil.exe" -i "$(TargetPath)"

The first line (which uses the TargetName parameter) removes anyexisting version of your tool from the GAC. The second line (whichuses the TargetPath parameter) installs the current version of yourtool into the GAC.

When I build a project, I sometimes get an error message thatstates Microsoft.VisualStudio.Shell.Interop is “not registered forCOM interop.”This doesn’t stop the project from building or inter-fere with the custom tool executing, so if you get that message,ignore it. However, to ensure that the PostBuild event script exe-cutes every time you recompile your DLL, set the dropdown listunderneath the PostBuild textbox to “When the build updates theproject output.”

To install your project in the GAC successfully, you must gen-erate an .SNK file that holds a digital signature (a “strong name”).Goto the Signing tab and check the “Sign the assembly” option. Fromthe dropdown list you just enabled, select <New…> to display theCreate a Strong Name Key dialog. Enter a valid file name in the “Keyfile name”textbox. The resulting file can be read with Notepad, so ifyou want to ensure that no one but you has access to the file, enter apassword in the dialog; if you’re not worried about that, thenuncheck the password option before clicking on the OK button.

Integrating with Windows and COMThe next step is to configure your project to have your DLL regis-tered with COM/Windows every time you build it. Still in ProjectProperties, find the “Register for COM interop” checkbox on theBuild tab (for C#) or Compile tab (for Visual Basic) and check it.You’ll need to revisit this option if you change the project’s configu-ration setting (for example, if you switch from Debug to Release),because the option is cleared when the configuration changes. Aspart of supporting COM, you also must go to the Application taband click on the Assembly Information button. Check the “Makeassembly COM-Visible”option on the resulting dialog.

Your custom tool must implement two interfaces: IVsSingle-FileGenerator and IObjectWithSite. You must assign your class aunique GUID to identify it to Windows. Simply add a System.Run-time.InteropServices.Guid attribute to your class and pass it a

FIGURE 1 Code-Generation Output The CodeGenerationInput.xmlfile has had its custom tool property set to SiteProcessor. When you switch away from the file, the SiteProcessor custom tool produces the code that Visual Studio put in the CodeGenera-tionInput.Generated.cs file.

Using a tool to generate repetitive code ensures consistency and reliability.

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 19

0309vsm_F2HowTo_16-23.v7 2/19/09 12:33 PM Page 19

Page 22: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

BeTheDataGuru

Visual Studio WPF/Silverlight SharePoint SQL Server PowerShellJava COM

Project5 12/11/08 4:42 PM Page 1

Page 23: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Data visualization for every need, every platform

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

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

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

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

AchieveAHigherStateOfDataVisualization

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

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

Page 24: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

B U I L D I N G C U S T O M T O O L S

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com22

GUID. In VS 2008, you can generate a GUID by selecting CreateGUID from the Tools menu. In VS 2005, open the VS Commandwindow and run the guidgen utility. Both methods open the CreateGUID dialog. Regardless of how you start the tool, pick option 4 togenerate a GUID compatible with the Guid attribute (the result willbe enclosed in braces that you’ll need to delete after pasting theGUID into your code).

Once you’re done, your class declaration will look like this inVisual Basic:

<System.Runtime.InteropServices.Guid( _"B2429B91-452D-4a95-A355-435337729EFB")> _Public Class TextGeneratorImplements _

Microsoft.VisualStudio.Shell.Interop. _IVsSingleFileGenerator

Implements Microsoft.VisualStudio.OLE.Interop. _IObjectWithSite

For VS to know about your custom tool, you need to add at least onekey to the Windows registry. The easiest way to do this is to add twomethods to your application: one to add the key and one to delete it.With the right attributes on those methods, they will be called auto-matically when your custom tool is registered or deregistered withWindows. (The changes you make to your project ensure that yourtool is registered and deregistered each time you build it.)

The code in these two methods is mostly—but not completely—boilerplate.You need to specify the version of VS that the custom toolworks with,provide a GUID that identifies the language of the projectsthat your tool will work with,provide the name you’ll use in the Cus-tomTools property and give a description. In addition, you have tocopy the GUID you generated for the GUID attribute into this code.

Rather than rewrite these methods each time you create a customtool, use a set of variables to hold the values and just update thosevariables from one tool to another. This VB code creates a tool forC# projects in VS 2008 called TextGenerator:

Shared VSVersion As String = "9.0"Shared CSLangGUID As String = _

"{fae04ec1-301f-11d3-bf4b-00c04f79efbc}"Shared ToolName As String = "TextGenerator"Shared ToolDesc As String = _

"Generates a class from text input"Shared ToolGUID As String = _

" B2429B91-452D-4a95-A355-435337729EFB "

<System.Runtime.InteropServices.ComRegisterFunction()> _

Public Shared Sub RegisterClass(ByVal typ As Type)Dim key As Microsoft.Win32.RegistryKeykey = Microsoft.Win32.Registry.LocalMachine. _

CreateSubKey( _"SOFTWARE\Microsoft\VisualStudio\" & VSVersion & _"\Generators\{" & CSLangGUID + "}\" & ToolName & "\")

key.SetValue("", ToolDesc)key.SetValue("CLSID", "{" + ToolGUID + "}")key.SetValue("GeneratesDesignTimeSource", 1)

End Sub

<System.Runtime.InteropServices.ComUnregisterFunction> +Public Shared Sub UnregisterClass(ByVal type As Type)

Microsoft.Win32.Registry.LocalMachine.DeleteSubKey( _"SOFTWARE\Microsoft\VisualStudio\" & VSVersion & _"\Generators\" & CSLangGUID & "\" & ToolName & "\", _False)

End Sub

If you want to support more than one language (for instance, ifyour tool works equally well in both C# and VB projects), just writeout two keys: one for each language. The language GUID to use forVB is 164B10B9-B200-11D0-8C61-00A0C91E29D5.

Using Standard CodeFor the four methods required by the interfaces your class has toimplement, you can use the same code for every custom tool youcreate. For example, the code for the GetSite and SetSite methodsnever changes:

Private _site As Object

Public Sub GetSite( _ByRef riid As System.Guid, ByRef ppvSite As _System.IntPtr) Implements _Microsoft.VisualStudio.OLE.Interop. _IObjectWithSite.GetSite

If Me._site = Nothing ThenThrow New _

System.ComponentModel.Win32Exception(-2147467259)End If

Dim objectPointer As IntPtr = _System.Runtime.InteropServices.Marshal. _GetIUnknownForObject(Me._site)

Try

Rather than rewrite these methods each time you create a custom tool, use a set of variables to hold the

values and just update those variables from one tool to another.

0309vsm_F2HowTo_16-23.v7 2/19/09 12:33 PM Page 22

Page 25: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

B U I L D I N G C U S T O M T O O L S

System.Runtime.InteropServices.Marshal. _QueryInterface(objectPointer, riid, ppvSite)

If ppvSite = IntPtr.Zero ThenThrow New _

System.ComponentModel.Win32Exception(-2147467262)End IfCatchEnd Try

End Sub

Public Sub SetSite(ByVal pUnkSite As Object) Implements _Microsoft.VisualStudio.OLE.Interop. _IObjectWithSite.SetSiteMe._site = pUnkSite

End Sub

The GetDefaultExtension method provides the extension that VSwill add to the file containing your generated code, so you may needto change it. This example causes VS to create a file with the formatfilename.generated.cs:

Public Function DefaultExtension( _ByRef pbstrDefaultExtension As _String) As Integer Implements _Microsoft.VisualStudio.Shell.Interop. _IVsSingleFileGenerator.DefaultExtensionpbstrDefaultExtension = ".generator.cs"Return 0

End Function

When VS is ready to generate your code, it calls the IVsSingleFile-Generator interface’s Generate method.VS passes the method thename of the file, the project’s namespace, the file’s contents, and aprogress bar. You must update the method’s two ByRef/outparameters with an array of bytes containing your generated codeand the length of your array.You should set the array parameter tonothing and the length parameter to 0 if your code generationfails.

Rather than rewrite the Generate method for every customtool, have the Generate method create a class called CodeGeneratorand call a method on it named GenerateCode.Always pass the Gen-erateCode method the name of the file, the project Namespace, thefile contents and the progress bar that VS passes to the Generatemethod. As a result, the Generate method becomes a set of boiler-plate code that looks the same in every custom tool:

Dim generatedCode() As Byte

TryDim cg As SiteGenerator = New CodeGeneratorgeneratedCode = cg.GenerateCode(wszInputFilePath, _

wszDefaultNamespace, bstrInputFileContents, _pGenerateProgress)

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

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

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

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

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrieval®

since 1991

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

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

� “For combing through large amounts of data,” dtSearch “leads the market” – Network Computing

� dtSearch “covers all data sources ... powerful Web-based engines” – eWEEK

� dtSearch “searches at blazing speeds” – Computer Reseller News Test Center

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

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CD/DVDsPublish for CD/DVDsPublish for CD/DVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win & .NETEngine for Win & .NETEngine for Win & .NET

New64-bitNew64-bit

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 23

0309vsm_F2HowTo_16-23.v7 2/19/09 12:33 PM Page 23

Page 26: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com24

B U I L D I N G C U S T O M T O O L S

rgbOutputFileContents(0) = _System.Runtime.InteropServices.Marshal. _AllocCoTaskMem(generatedCode.Length)

System.Runtime.InteropServices.Marshal.Copy( _generatedCode, 0, rgbOutputFileContents(0), _generatedCode.Length)pcbOutput = generatedCode.Length

CatchpcbOutput = 0rgbOutputFileContents(0) = IntPtr.Zero

End Try

Generating CodeYou’re now finally ready to start writing the code that’s unique to your code generator. Start with a standard version of your CodeGenerator class, which writes to the output file the parameterspassed to it from the Generate method. This code lets you checkthat your custom tool works and is getting passed what you expect:

Public Function GenerateCode(ByVal FilePath As String, _ByVal Namespc As String, ByVal FileContents As String, _ByVal Progress As _Microsoft.VisualStudio.Shell.Interop. _IVsGeneratorProgress) _As Byte()

If FileContents = "" ThenThrow New Exception("No content")

End IfProgress.Progress(0, 100)Dim generatedCode As StringgeneratedCode = "Namespace: " & Namespc & ", " & _

"File name:" & FilePath & ", " & _"File contents:" & FileContents

Progress.Progress(100, 100)Return System.Text.Encoding.UTF8.GetBytes( _

generatedCode)

End Function

You must start a new copy of VS to test your custom tool. After thenew copy starts, create a project, add a file, fill it with some text,and set the file’s CustomTool property to the name of your customtool. In VS 2008, your custom tool runs as soon as you switchfocus away from the file; in VS 2005, you can run your custom toolby closing the file. In either version of VS, you can also right-clickon the file in Solution Explorer and select “Run custom tool.”

Whatever method you choose, you should see a new file addedunder your existing file with the file extension you specified in theGetDefaultExtension method and holding the output from yourGenerateCode method.

Of course, it might not work the first time. Problems usuallyare related to registering your custom tool with Windows. If this isthe case, the message you’ll get will typically say that your customtool cannot be found. A number of typical problems can occur.

First, the GUID you used in the GUID attribute on your classmight be different than the Guid you set the ToolGUID variableto. Second, the two methods that add and remove the keys to theWindows registry might be wrong. Check that you’ve got the rightversion number for VS and the right GUID for the languageyou’re testing in. For example, did you create a key for C# but thentest your custom tool in a VB project? It’s helpful to open RegEditand look at the keys you’re generating to see if they look like theother keys in the Generators section.

Finally, your custom tool might not have gotten into theGAC. If a problem exists with your PostBuild event, you’ll see amessage in your Output window. You can also try removing yourcustom tool from the GAC by using gacutil –u nameofyourproject.If you get a message stating that your assembly couldn’t be found,then you’ll know that you have a problem getting your tool intothe GAC.

When you’re ready to start generating code, replace the line inyour GenerateCode method that sets the generatedCode variablewith a line that sets the variable to a string containing your code.This example creates a “Hello,World”class:

generatedCode = "namespace " & Namespc & _"{public class NewClass{public string" & _" SayHello(string Name){return ""Hello, "" + Name;}}}";

You now have a working custom tool. True, the interesting work isstill left to do: reading your file’s input and turning it into real code.But that’s also the fun part. VSM

Peter Vogel ([email protected]) is a .NET consultant, author andinstructor living in Goderich, Ontario, Canada.

GO ONLINE

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

READ & DOWNLOAD

VS0903PV Read this article.

When you’re ready to start generating code, replace theline in your GenerateCode method that sets the

generatedCode variable with a line that sets the variable to a string containing your code.

0309vsm_F2HowTo_16-23.v7 2/19/09 1:02 PM Page 24

Page 27: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 25

SPOTLIGHT ON GRAPHICS, IMAGING AND MAPPING

The following advertising section showcases companies offering solutions for your graphic, imaging and mapping needs.

Special Advertising Section

0309vsm_025 2/19/09 4:47 PM Page 25

Page 28: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Spotlight on Graphics, Imaging & Mapping

Setting the standard in geospatialapplication development.

Interactive Mapping is our Passion

A platform designed to allow you to rapidly visualize,

manage and analyze geospatial data. MapDotNet includes

a web services based server, an SDK with support for

Silverlight™, WPF and AJAX, and MapDotNet Studio for

modernized interactive map design on your desktop.MapDotNet with

Silverlight Interface

Microsoft recommends MapDotNet when you need to

intergrate existing Geographic Information Systems (GIS)

with Microsoft Virtual EarthTM

.

Download 60 day trial at www.mapdotnet.com

or call us at (850) 893-6741.

© Copyright 2009, ISC, all rights reserved.

t ISC, our mission is to provide you with the best toolsand software you will find for fulfilling your organization’s

geospatial visualization and analysis needs. The MapDotNetproduct line is a perfect fit for any organization that supportsMicrosoft’s .NET platform and is looking for cost-effectivegeospatial solutions.

MapDotNet UX is the comprehensive Web-enabled geospatial platform for enterprise applications and Web sites.MapDotNet UX brings a new level of user experience to theMapDotNet series with extensive support for Windows Presentation Foundation (WPF) and Silverlight, as well asAJAX. With a focus on user experience, MapDotNet UX is the toolkit for GIS integration with consumer-based mapping platforms.

A

www.mapdotnet.com

The MapDotNet UX product line includes:

• MapDotNet UX Studio: a tool for designing interactive maps for Silverlight, WPF and AJAX applications. It includes utilities for tile cache management and spatial data transfer, with support for Microsoft SQL Server 2008.

• MapDotNet UX Web Services: WCF-based Web services that provide an open interface for server-based spatial data services and the MapDotNet WPF map rendering engine,which takes advantage of accelerated graphics hardware. It islicensed per server, not per processor.

• MapDotNet UX SDK: WPF and Silverlight 2.0 controls, a Virtual Earth™ tile handler for use in AJAX applications, andan extensive class library.

MapDotNet isa product of

Setting a New Standard in Geospatial Application Development

0309vsm_026 2/19/09 11:37 AM Page 26

Page 29: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 27

Spotlight on Graphics, Imaging & Mapping

Setting the standard in geospatial application development.

Interactive Mapping is our PassionAn entire GIS platform designed to

allow you to rapidly visualize, manage

and analyze geographic data. The

MapDotNet Platform consists of

MapDotNet UX for Silverlight & WPF

and MapDotNet Server for AJAX.

Download a 60 day trial at www.mapdotnet.comor call us at (850) 893-6741.

© Copyright 2009, ISC, all rights reserved.

MapDotNet with

Silverlight Interface

Copyright © 2009 ESRI. All rights reserved. The ESRI globe logo, ESRI, ArcGIS, www.esri.com, and @esri.com are trademarks, registered trademarks, or service marks of ESRI in the United States, the European Community, or certain other jurisdictions.

Other companies and products mentioned herein may be trademarks or registered trademarks of their respective trademark owners.

1-800-447-9778info@

GIS—Better Decisions through Modeling and Mapping Our World

ESRI Philosophy

ESRI believes that better information makes for better decisions.Our reputation is built on contributing our technical knowledge, our special people, and our valuable experience to the collection, analysis, and communication of geographic information. Foundedin 1969, ESRI is the leading developer of GIS software with morethan 300,000 clients worldwide.

Contact us today to learn how ESRI’s GIS is helping to manage and improve business operations around the world.

www.leadtools.com/vsm2009

The World Leader in Imaging Development SDKs

LEAD Technologies is thedeveloper and publisher ofLEADTOOLS, the award-winning line of developmenttoolkits. The result of 18 years of development, a LEADTOOLS SDK literallyputs millions of lines of code at the fingertips of developers.The LEADTOOLS line helps programmers integrate color,document, medical, multimedia,and vector imaging projects intotheir applications quickly and easily, offering developmentsupport for 150+ File Formats, Image Compression,Image Display, Annotations, Forms Recognition, DocumentClean-Up, PDF and PDF/A, OCR, Barcode, Scanning/Capture and DICOM.

Founded in 1991, Pegasus Imaging is trusted to deliverimaging software development kits (SDKs) and tools featuring superior image viewing, compression, recognition,and image-editing technologies. The company exceedsspeed and quality requirements for document imaging,forms processing, medical imaging, DICOM, photo imaging,video applications and more. Technology is delivered asMicrosoft .NET, ActiveX, and Silverlight controls, WF ActivityLibraries, DLLs and applications. Multiple 32-bit and 64-bitplatforms are supported, including Windows, WindowsMobile, Java, Java ME (mobile), Linux, Sun Solaris and IBMAIX. Download full-featured trials and demos today.

www.pegasusimaging.com

0309vsm_027 2/19/09 12:46 PM Page 27

Page 30: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Spotlight on Graphics, Imaging & Mapping

LEAD Technologies, Inc. is the publisher of LEADTOOLS, the world leader in imaging componentsfor developers. LEADTOOLS SDKs are used by virtually every Fortune 1000 company, includingMicrosoft, HP, Kodak, Sony, GE and Siemens.LEADTOOLS provides developers easy access to decades of expertise in developing color, grayscale,document, medical, vector and multimedia imaging technology. Install LEADTOOLS to eliminatemonths of research and development, and add high levels of quality, performance and functionality.

Document Imaging EngineLoad and save over 150 different formats including PDF/A and XPS. Add specialized bitonal imageprocessing, viewing, high speed scanning, annotations, and document image compression to yourbusiness applications. Includes a powerful document clean-up engine to despeckle, deskew, removelines, borders, hole-punches and inverted text and make other corrections. Display features includefast view port rotation for instant rendering and optimized scale to gray and favor black. Maximizescanner performance with auto-detection of the fastest settings for image acquisition from TWAIN 2.0and WIA devices. Mark-up images with the industry’s most comprehensive and highly customizableannotation engine including notes, pointers, redactions, highlights, stamps, measurement tools andaudio/video. Save disk space and network bandwidth with LEAD’s advanced bitonal image compressionalgorithms for JBIG2, MRC, CCITT G3/G4 and JPEG 2000. Automatically recognize and classify forms.Convert images to editable documents with multi-threaded OCR/ICR/OMR modules. Detect, read andwrite a wide variety of linear and 2D barcode symbols.

Medical Imaging EngineDevelop state-of-the-art imaging applications for use by the healthcare industry with high and lowlevel DICOM data manipulation and secure DICOM communication. A customizable display containerfeatures built in viewing tools. Extend PACS access to the Internet, including web based reading andconsulting with HTML or rich clients and web services. Support for extended grayscale and color imageprocessing and compression such as JPEG, JPEG 2000 and MPEG-2. LEADTOOLS provides high levelsupport for waveforms, printing, digital signatures, overlays, softcopy presentation, modality LUT,VOI, LUT and DICOM annotations and graphics objects. Includes sample source code for DICOM serverand client services to query, retrieve, store and Modality Worklist.

Imaging EngineIncorporate digital imaging functionality into your applications. Load, save and convert over 150 formatsincluding TIFF, EXIF, PDF and PSD supporting a wide range of color spaces and compression typesincluding JPEG, JPEG XR, JPEG 2000, CCITT G3/G4, LZW and ZIPLIB. Easily capture from screen and any32/64 bit TWAIN 2.0 or WIA compliant device. Apply image transforms, color space conversion and 200+region aware image processing routines. Speed up development with high level display controls withbuilt-in features such as pan, zoom and magnify, thumbnail browser and imaging common dialogs.

Multimedia Imaging EngineEnable your Windows and Web applications with multimedia capture, playback, conversion andediting. Create and burn DVDs with menus. Easily add TCP/UDP network streaming and HD broadcast.Load, save and convert MP4, AVI, MPEG, MP3, WMV, 3GP, OGG, FLV (YouTube and HD Flash) and otherfile types. Add support for portable devices including iPhone/iPod, PSP, ZEN, Zune, SmartPhone andothers. Encode, decode and transcode with LEAD’s optimized software codecs including H264, MPEG4,H263, and MPEG-2 or any third party codecs. LEAD multiplexers and demultiplexers such as MPEG-2Program and Transport, MP4, OGG and FLV are available.

Free 60 Day Evaluation! www.leadtools.com/vsm 866 530-3399LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies.

Annotations

Form Recognition

Document Clean-up

Barcode

Key Features and Benefits

• Load and save over 150 formats to disk or SharePoint servers.• Specialized bi-tonal image display and processing.• High speed scanning with TWAIN 2.0 and WIA including support for unattended batch scanning.• Fast and Accurate Forms Recognition and Forms Processing.• Convert images to documents with multi-threaded OCR/ICR/OMR.• Detect, read and create linear and 2D barcodes.• Improve recognition performance & image quality with document image clean up tools.• Efficiently store and transmit images with the industry’s best compression engines.• Bitonal, Color and Extended Grayscale Compression and Processing.• Specialized versions of LEADTOOLS for document, color, medical and multimedia development.• Industry Leading Technical Support.

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com28

0309vsm_028 2/19/09 11:45 AM Page 28

Page 31: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Develop your application with the same robust imaging technologies used by Microsoft, HP, Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affairs Hospitals.

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

•Image Formats: All industry standards including TIFF, EXIF, PDF, JPEG/JPEG2000, DICOM, PCL, DWG and hundreds more.•Image Compression: From standard JBIG, JBIG2, ABIC, JPEG and CCITT G3/G4 to LEAD’s specialized ABC, CMP and CMW compression.•Display Controls: Scroll, zoom, pan, magnify glass, brightness/contrast/gamma, window level.•Image Processing: 200+ filters, transforms and color conversion functions with extended grayscale (10 to 16-bit) support.•OCR/ICR/OMR: Full page or zonal multi-threaded recognition with formatted output including PDF, DOC and TXT for Win32 and x64.•Barcode: Read/write all industry standard 1D and 2D barcodes (DataMatrix, PDF417, MicroPDF417, QR Code and more).•Forms Recognition and Processing: Automati-cally identify forms and extract user filled data.•Document Cleanup/Preprocessing: Deskew, despeckle, line and border removal, registration marks and more.•PDF and PDF/A: Read/write raster and text searchable PDF files.•Annotations: Interactive UI for documentmark-up, redaction and image measurement (including support for DICOM annotations).•Grayscale Imaging: Display and process signed/unsigned 10-16 bit, 32 bit data.

•Medical Web Viewer Framework: Plug-in enabled framework to quickly build high-quality, full-featured, web-based medical image delivery and viewer applications.•Medical Image Viewer: High level display control with built-in tools for image mark-up, window level, measurement, zoom/pan, cine, and LUT manipulation.•DICOM: Full support for all IOD classes and modalities defined in the 2008 DICOM standard (including Encapsulated PDF/CDA and Raw Data).•DICOM Communications: Full support for DICOM messaging and secure communication enabling quick implementation of any DICOM SCU and SCP services.•WPF (XAML): Viewer, Image List, Annotations, Transitions and WIC Codecs.•AJAX Web Form Image controls for developing rich web applications.•JPIP Client and Server components for interactive streaming of large images and associated image data using the minimum possible bandwidth.•Scanning: TWAIN 2.0 and WIA (32 and 64-bit), autodetect optimum driver settings for high speed scanning.•DVD: Play, create, convert and burn DVD images.•Multimedia: Capture, play, stream and convert MPEG, AVI, WMV, MP4, MP3, OGG, ISO, DVD and more.

Free 60 Day Evaluation! www.leadtools.com/vsm 866 530-3399LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies.

Mark-up DICOM Medical

Form Recognition & Processing

Multimedia

Document Barcode

LEADTOOLS v.16 – .NET, WPF, WCF,WF, C API, C++ Class Lib, COM & more!

Project5 2/6/09 8:48 AM Page 1

Page 32: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Spotlight on Graphics, Imaging & Mapping

he year 2008 endedwith an acquisition thatshook up the imagingmarketplace, shockingcompetitors and

pleasantly surprising many industryanalysts, vendors, OEMs and individual enterprises. PegasusImaging and AccuSoft’s imagingbusinesses combined to becomeone imaging technology power-house. Three weeks later, theindustry saw them acquire a thirdvendor Tasman Software. Today,the new company is uniquely positioned to be the largest andmost experienced provider of imaging software developmentkits (SDKs) and image-viewing solutions in the world.

With decades of experience behind them, the companieshave joined together to merge solid product lines, extraordinary talent and an incredible amount of intellectualproperty. Pegasus Imaging is expanding to create anunbeatable combination of imaging technologies from a single-source provider.

Pegasus Imaging delivers document and image viewing,capture, image processing and several recognition technologies within easy-to-use SDKs. The products areused in various development environments and on multipleplatforms. Find SDKs for .NET, ActiveX, Silverlight,ASP.NET, WF activities (that can be used with MicrosoftSharePoint), Java, Java ME (mobile), Linux, Solaris, AIX,Mac, 32-bit, 64-bit and the list goes on. Two powerful Web-based image viewers are also available, each offeringtheir own individual set of benefits.

Pegasus Imaging delivers solutions for:

• Image and Document Viewing• Barcode• Image Compression• OCR, ICR, OMR (Text and

Mark Recognition)• Image Processing, Cleanup, Editing• Forms Processing, Recognition, Dropout• Scanning, Capture • Photo Image Enhancement• Video Compression, Decompression• PDF, TIFF and More

ImagXpress and ImageGear are the flagship imaging SDKsto evaluate first. Both provide superior image viewing, processing, compression, annotation, scanning and printing.Software engineers can then add Barcode Xpress to accelerate document archiving application development andassist in process automation efforts. The FormSuite SDKbundles industry-leading forms processing, form recognition,form dropout, image cleanup and editing, zonal OCR, ICRand OMR. PDF Xpress offers advanced PDF support, andOCR Xpress adds full-page text recognition. Thousands ofsoftware engineers rely on these products. Download anddiscover the many advantages of being a Pegasus customer.

Pegasus Imaging is committed to delivering superior technical support and customer service by trained, in-houseteams dedicated to help meet customer needs. Productsare offered as full-featured trials prior to licensing. PegasusImaging is a leader in research and development of imagingtechnologies, and is the provider of choice for developers ofdocument imaging, health-care imaging and photo/videoimaging solutions worldwide.

Pegasus Imaging: Your Single Sourcefor Imaging SDKs

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com30

www.pegasusimaging.com

T

0309vsm_030 2/19/09 11:53 AM Page 30

Page 33: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Project2 2/9/09 11:57 AM Page 1

Page 34: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

C# developers create types every day. But how often do developers think about how welltheir types behave with the type system? Do they write the methods and define the behav-ior their users will expect one day? What capabilities will the .NET Framework expectfrom any type?

Answering these questions isn’t much work, but it’s probably a bit more than you do today. Takinga look at the capabilities the compiler gives to anonymous types also serves as an excellent tutorial onwhat you should consider when you create your types.

Begin by creating a simple C# program that creates an anonymous type and prints each of the values inthe sequence of those objects (see Go Online,p.35, to access a sample listing).The program isn’t that inter-esting in itself,but it’s instructive to look at the code the compiler generates for that anonymous type.

Now it’s time to create a modified version of the code generated for this type (see Listing 1, p. 35).The modified version changes many of the names because the compiler uses special characters foranonymous types to avoid collisions with user-created names.Also, the compiler creates a generic class,which it uses for some other optimizations.

Let’s examine the important design decisions and the features added to the anonymous type. First,the accessibility of the class is internal. How often do you create internal classes? If your default choice ispublic, you should change that habit. How many classes do you create that will never be accessed outsideof the current assembly? Are those public? If so, you’re creating public classes unnecessarily, and you’readding names to your public API that aren’t necessary. That creates more confusion for your users. Theyaren’t supposed to use some of these classes, and yet, those classes show up in IntelliSense and in your

TECHNOLOGY TOOLBOX

VB.NET

C#

SQL Server 2005

ASP.NET

XML

VB6

Taking a careful look at thecapabilities the compilergives to anonymous typesprovides an excellent tutorial on what you shouldconsider when you createyour types—includingwhether they are classesor structs.BY BILL WAGNER

C # CO R N E R A N O N Y M O U S T Y P E S

Create Anonymous Types

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com32

ILLU

ST

RA

TIO

N F

RO

M IS

TO

CK

PH

OT

O.C

OM

0309vsm_C#Corner_32-35.v7 2/19/09 12:45 PM Page 32

Page 35: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

C # C O R N E R » A N O N Y M O U S T Y P E S

API docs. This essentially pollutes your users’ experience with yourapplication. You should always choose the least-visible access toachieve your goal.

Anonymous types are sealed. This is an obvious choicebecause you can’t derive a new type from something you can’tname. Your job is somewhat more difficult. You need to examineyour types and make an explicit decision to support or denyderived classes from your type. If you believe developers shouldn’textend your type, make that statement explicit by using the sealedkeyword. If you believe developers will want to extend your type,pay careful consideration to where derived types will want toextend or change the behavior of your type. Make those methodsvirtual and provide explicit guidance on the extension pointsyou’ve created. You should always support or prohibit derivationexplicitly; don’t leave it to client developer interpretation.

Check the Anonymous TypeNext, you should check whether the anonymous type is immutable.(VB.NET supports both mutable and immutable anonymoustypes.) Immutable types are simpler for many reasons:You can vali-date state in constructors and know they’re always valid; immutabletypes can be shared safely across threads; and immutable types sim-plify testing because state changes can’t affect later methods. How-ever, it’s overly simplistic to say that every type in your programsshould be immutable; that’s simply not practical.You should preferimmutable types whenever possible. When design issues force youto create mutable types, you should understand that those types aremore complicated, will introduce more errors and will introducemore complications in testing. The more related data fields in atype, the more complicated the relationships are.

There are three methods added to every anonymous type bythe C# compiler: overrides of Object.ToString(), Object.Equals()and Object.GetHashCode(). Object.ToString() helps in even thissmall sample. You can print the anonymous type object instead ofwriting extra code to print each of the fields from the anonymoustype. Over the course of a larger application, a proper ToString()method makes it easier to use your type any time you want to displaythe information in an object for your users, or even in the debuggerfor other developers.You should always create a ToString() methodthat displays the best choice of information for your type.

The overrides of Object.Equals() and Object.GetHashCode()force anonymous types to use value semantics rather than refer-ence semantics. That means two objects are equal if they containthe same information, rather than if they refer to the same object. Ifyou modify Equals(), you do need to create a corresponding GetH-ashCode() to ensure that objects that are equal always return thesame hash value. When you create your own types, you can chooseto follow either reference semantics or value semantics. In general,types that are primarily data-storage types should follow valuesemantics. Types that are primarily defined by their behaviorshould follow reference semantics. Once again, make that anexplicit decision: Determine which makes more sense for yourtype, and implement that appropriately.

Critique on Anonymous TypesOf course, nothing is perfect, including the implementation ofanonymous types by the C# compiler. When you create your owntypes, you should consider additional decisions as part of every typeyou create. The first of these is related to equality semantics. TheObject.Equals() override uses the ultimate base class,System.Object.As of .NET 2.0, you have a generic interface for equality: IEquat-able<T>.Anytime you override System.Object.Equals(),you shouldimplement IEquatable<T> for your type. For example, you shouldadd IEquatable<T> support if your type is coded by hand:

internal sealed class HandCodedPoint : IEquatable<HandCodedPoint>

The implementation of Equals() is a strongly typed version of theSystem.Object override. Notice that you can now defer the imple-mentation of System.Object.Equals to your strongly typed version:

#region IEquatable<AnonymousTwo> Memberspublic bool Equals(HandCodedPoint other){

return (((other != null) &&EqualityComparer<int>.Default.Equals(this.xField, other.xField)) &&EqualityComparer<int>.Default.Equals(this.yField, other.yField));

}#endregionpublic override bool Equals(object value){

return Equals(value as HandCodedPoint);}

If you’ve created your own version of Equals() and implementedIEquatable<T>, you should create your own operator == andoperator !=. Because you’ve already written the logic in yourIEquatable<T> method, you can reuse that implementation inyour operator ==.Your operator != is the inverse:

public static bool operator ==(HandCodedPoint left, HandCodedPoint right)

{if (left == null)

return right == null;return left.Equals(right);

}public static bool operator !=(

HandCodedPoint left, HandCodedPoint right)

{return !(left == right);

}

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 33

0309vsm_C#Corner_32-35.v7 2/19/09 12:45 PM Page 33

Page 36: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

The lesson to take away from these examples: Equals touches manymethods; make sure they’re all consistent.

You should also consider implementing IComparable<T>(and the non-generic IComparable) if your type has an obviousordering relation. This point type has an obvious ordering relation:using the distance of a point from the origin. You can compare

those distances and define an ordering relation on points:

public int CompareTo(HandCodedPoint other){

// Something is greater than nothing:if (other == null)

return 1;int distanceSquared =

xField * xField + yField * yField;int otherDistanceSquared =

other.xField * other.xField + other.yField + other.yField;

return distanceSquared.CompareTo(otherDistanceSquared);

}public int CompareTo(object obj){

return CompareTo(obj as HandCodedPoint);

}

Implementing IComparable implies youhave also defined operator > and operator<. You’ve already written the algorithm, soall you need to do is add the signature andcall the methods you’ve already written:

public static bool operator >(HandCodedPointleft, HandCodedPoint right)

{if (left == null)

return false;else

return left.CompareTo(right) > 0;}public static bool operator <(

HandCodedPointleft, HandCodedPoint right)

{if (left == null)

return right != null;else

return left.CompareTo(right) < 0;}

HandCodedPoint implements both ICom-parable<T> and IEquatable<T>, so youshould add the operators >= and <=:

public static bool operator >=(HandCodedPoint

The .NExT Step In Document

and Photo Imaging

www.atalasoft.com

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

support, AJAX Vector Annotations including FreeHand, WPF annota-

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

footprint web applications in C# and VB.NET—Take document and

photographic imaging to the .NExT step.

Visit Atalasoft.com for web demos, video tutorials, and a free trial.

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

DotImage 7.0—More Powerful,

with Zero-Footprint Imaging, and

3 Months of Free Gold Support.

New

DotImage 7.0

Release

C # C O R N E R » A N O N Y M O U S T Y P E S

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com34

0309vsm_C#Corner_32-35.v7 2/19/09 12:45 PM Page 34

Page 37: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

C # C O R N E R » A N O N Y M O U S T Y P E S

left, HandCodedPoint right){

return (left == right) || (left > right);}public static bool operator <=(HandCodedPoint

left, HandCodedPoint right){

return (left == right) || (left < right);}

This is a fair amount of work and I don’t recommend adding it toevery single type you create. However, you should give it somethought and make sure you know when you should and shouldn’tcare about certain behaviors. Obviously it doesn’t make any senseto define an ordering relation between windows or many othertypes you create.

Anonymous types include a fair amount of code to imple-ment the behavior that you would expect on every type.You shouldfollow the same guidelines and create methods that all your userswill expect or implement in their own version. You should also

spend some time thinking of the basic behavior that’s expected ofyour types, and create that behavior for your users. Rather than justignoring the basic behavior, decide which behavior should beimplemented in your type and create it. VSM

Bill Wagner, author of “Effective C#: 50 Specific Ways to ImproveYour C#” (Addison-Wesley Professional, 2004) and “More EffectiveC#: 50 Specific Ways to Improve Your C#” (Addison-Wesley Profes-sional, 2008), has been a commercial software developer for the past20 years. He is a Microsoft Regional Director and a Visual C# MVP.His interests include the C# language, .NET Framework and soft-ware design. E-mail Bill at [email protected].

GO ONLINE

Use these Locator+ codes at VisualStudioMagazine.com to go directly tothese related resources.

READ & DOWNLOAD

VS0903CC Read this article and download the sample code online.

internal sealed class AnonymousOne{

// Fieldsprivate readonly int xField;private readonly int yField;

// Methodspublic AnonymousOne(int x, int y){

this.xField = x;this.yField = y;

}

public override bool Equals(object value){

var type = value as AnonymousOne;return (((type != null) &&

EqualityComparer<int>.Default.Equals(this.xField, type.xField)) &&

EqualityComparer<int>.Default.Equals(this.yField, type.yField));

}

public override int GetHashCode(){

uint num = 0xdd9cb371;num = (0xa5555529 * num) +

(uint)EqualityComparer<int>.Default.GetHashCode(this.xField);

return (int)((0xa5555529 * num) +

(uint)EqualityComparer<int>.Default.GetHashCode(this.yField));

}

public override string ToString(){

StringBuilder builder = new StringBuilder();builder.Append("{ x = ");builder.Append(this.xField);builder.Append(", y = ");builder.Append(this.yField);builder.Append(" }");return builder.ToString();

}

// Propertiespublic int x{

get { return this.xField; }}

public int y{

get { return this.yField; }}

}

LISTING 1 This code is similar to the code created by the compiler for anonymous types. The compiler creates a generic type in order to reusesome code. Also, the compiler generates names that are illegal for handwritten code to avoid collisions with user-defined types.

C# REPRESENTATION OF AN ANONYMOUS TYPE

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 35

0309vsm_C#Corner_32-35.v7 2/19/09 12:45 PM Page 35

Page 38: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com36

BY KATHLEEN DOLLARDDISPLAY MULTIPLE PAGES IN SILVERLIGHT

Technologies mentioned in this article include Silverlight, Windows Presentation Foundation,Visual Studio Team System, Visual Basic and C#.

QHow can I change forms in Silverlight so my applicationworks in exactly the same way in both my Silverlightand WinForms applications?

A Silverlight Forms correspond roughly to Pages in Sil-verlight, and each Silverlight application has exactlyone Page. So, I’d like to rephrase your question to

something like this: “How can I make it seem as though I’mchanging forms?” Once you ask the question this way, you’rehalfway to the answer.You provide a page that acts as a containerfor user controls,and each user control corresponds to a form inyour existing application (see Figure 1).Pages can have only onecontent element, so you generally use a container such as a gridto hold your user controls. The grid is a nice container to usebecause it lets you overlay controls when needed; it also lets youinclude features that behave consistently across all your usercontrols.This is similar to using a Master Page in ASP.NET.

Q I’ve heard there’s a TreeView control for Silverlight 2.0,but I don’t see it in the toolbox. I’m having a hard timefiguring out what controls are in Windows Presentation

Foundation [WPF] and Silverlight, respectively.

AMicrosoft is releasing controls for both WPF and Silverlight as Toolkits. This avoids delaying therelease of important tools until a normal ship cycle.

In addition to the controls it ships with, Silverlight has apreview of a Visual State Manager in the main tool, while WPFhas a preview in the WPF Toolkit. The Silverlight Toolkit alsoincludes a preview of an Implicit Style Manager that recreatessome functionality that’s inherently part of WPF.

The Visual State Manager in Silverlight allows you todescribe states for controls, and defaults for what the controlsshould look like when they’re in each state. It also allows youto dictate how long the transition into a given visual lookshould take (the length of the animation). When creatingapplications, programmers can override the standard stateappearance with their own. The Blend tooling for this isextremely good, making it much easier to customize controlsthan in WPF, where individual styles and triggers are neededto provide this functionality.

The Implicit Style Manager introduced to Silverlight asa preview in the Silverlight Toolkit allows you to apply thestyle based on type, rather than by requiring an explicit styledeclaration on each instance of each control. This isn’t asautomatic as the WPF approach because each control isbased on a container that applies styles as a theme, and thecontainer must be placed in each user control. Also, you can’tchange the theme at runtime. The good news is that the Silverlight Toolkit contains a great set of themes to get you started.

Q I have a bug in a case statement that I don’t understand.This code works correctly when the direction is right orbelow. It throws an InvalidOperationException when

None (the default) is passed, which it shouldn’t do. Direction isan enum. Can you tell me what’s wrong?

Select Case mDirectionCase Direction.Rightlocation = New Point(mPopup.ActualWidth, 0)

location = New Point(0, -mPopup.ActualHeight)Case ElseThrow New InvalidOperationException()

End Select

Case Direction.Below Or Direction.None

Learn how to display multiple pages in Silverlight and discover the toolsand controls that ship with it; track down a bug in a case statement; andtake advantage of helpful tips for trying to obtain a clean Code Analysis.

Ask Kathleen

0309vsm_AskKat.36-38.v6 2/19/09 1:27 PM Page 36

Page 39: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

A S K K AT H L E E N » S I LV E R L I G H T

AThis is an easy mistake to make because Or actsas a bitwise or Boolean operator depending onthe operands. In this case, the operands for

the Or operator in the line I’ve highlighted act as a bitwise operator. I’m going to guess that the value ofDirections.None is zero, which is a good choice for thedefault value. If that’s true, the result of the Or operationis Direction.Below. This is why it works for everythingexcept the value of Direction.None.

Just use a comma to separate the different valuesyou wish to match:

Case Direction.Below, Direction.None

If you make this mistake in C#, you fix it by using twoadjacent switch statements with no break statement:

switch (mDirection){case Direction.Right:

location = new Point(mPopup.ActualWidth, 0);break;

case Direction.None:case Direction.Below:

location = new Point(0, -mPopup.ActualHeight);

break;default:break;

}

Q I’m trying to get a clean Code Analysis. Unfortunately, thecode in one of my classes is giving Code Analysis warnings.My boss says we need to comply fully with Code Analysis

without suppressing any messages. The code looks like this:

private void WriteMessage(string message){string text = String.Empty;if (mOwner.Content != null){text = mOwner.Content.ToString();

}System.Diagnostics.Debug.WriteLine(

text + ":" + message);}

The warning is:

CA1801 : Microsoft.Usage : Parameter 'message' of'Class1.WriteMessage(string)' is never used. Remove theparameter or use it in the method body.

Why does Code Analysis give these errors when the parameter is obviously used?

ACode Analysis analyzes the Release Assembly. The compiler removes the Diagnostics.Debug line when com-piling. If you check the IL through Reflector,you’ll see that

the only code using the parameter and variable doesn’t exist withinthe Release Assembly. Interestingly, the same code in VB gives a sec-ond warning:

CA1804 : Microsoft.Performance : 'MenuProvider.WriteMes-sage(String)' declares a variable, 'text', of type'String', which is never used or is only assigned to. Usethis variable or remove it.

There are a few ways to work around these problems, but your bossis making a mistake when he insists on setting a goal for full CodeAnalysis compliance without suppressing any items. A good solu-tion in this case is to formally ignore the warnings. If you right-click on the warning, you’ll have the option of ignoring it in anexternal file or in the source code. I much prefer suppressing themessages in source code and always including a Justification. Thislets other coders know why you decided to ignore the warning.

You can’t just remove the code with conditional compilationbecause other code is calling the method. A slightly more complexapproach would be to alter the class to be a partial class and add anew declaration for a partial method with the same signature

FIGURE 1 Display Several Silverlight “Forms” Simultaneously. Silverlightruns in a browser, so there’s only one Page that serves as the RootVisual or visualentry point for your application. You can’t change the RootVisual as your applicationruns. When your application needs to display several “forms” at different times, create one Page to serve as a navigation container and switch out user controls thatcontain the “forms” of your application. The Page might be empty or contain visualelements common to all of your user controls.

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 37

0309vsm_AskKat.36-38.v6 2/19/09 1:47 PM Page 37

Page 40: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

A S K K AT H L E E N » S I LV E R L I G H T

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com38

(name and parameters) as your WriteMessage method. You don’tneed a second class declaration; instead, change the existing one toinclude the keyword partial. Then wrap your actual WriteMessagemethod entirely in a #if DEBUG directive:

partial void WriteMessage(string message);

#if DEBUGpartial void WriteMessage(string message){// Code as above

}#endif

When you compile this code for debugging,Visual Studio will findthe real WriteMessage method, and the method will work asexpected. When you compile for release, the DEBUG constant willbe missing, so your implementation of WriteMessage will be miss-ing. Due to the partial class declaration, the compiler will removeall calls to your WriteMessage method.

This only works because your method is private and void. It alsoprovides a slight runtime performance improvement because callswon’t be made to the method, and the string concatenation won’t beperformed.This performance improvement will be small,but can stillprove significant if you call this method a number of times.

Q I’m trying to get a clean Code Analysis run for some VisualBasic code, but I’m getting the following warnings:

Warning 3 CA1034 : Microsoft.Design : Do not nest type 'Menu-Item.MenuItemClick2EventHandler'. Alternatively, change itsaccessibility so that it is not externally visible.

SilverlightMenuLibrary

Warning 4 CA1003 : Microsoft.Design : Visual Basic generatesEventHandler delegates for events that use the followingpattern: Event MyEvent(ByVal Sender As Object, ByVal e asMyEventArgs). Change the event that defines EventHandler'MenuItem.MenuItemClick2EventHandler' to useEventHandler<T> by defining the event type explicitly, e.g.Event MyEvent As EventHandler(Of MyEventArgs).

SilverlightMenuLibrary

Warning 4 (and possibly Warning 3) is related to this declaration:

Public Event MenuItemClick(ByVal sender _As Object, ByVal e As MenuItemClickEventArgs)

How do I fix this?

APrior to the introduction of generics in .NET 2.0 (VS2005), each unique event with a unique set of parametersneeded an explicit declaration of a delegate that corre-

sponded to the event signature. By convention, these events werenamed with the name of the event followed by “EventHandler.” Ifyou checked the code in Reflector—which is still free, but now dis-tributed by Red Gate Software Ltd.—you’d see a delegate within theclass that was generated by the compiler:

Public Delegate Sub _MenuItemClickEventHandler( _ByVal sender As Object, _ByVal e As MenuItemClickEventArgs)

Code Analysis is warning you that there’s a nested delegate. Thiswas appropriate for the generated delegate because it limited thepotential for naming collisions. If you’d like to quiet the errors, youcan use the code suggested by the second error:

Public Event MenuItemClick _As EventHandler( _Of MenuItemClickEventArgs)

This code uses the generic event handler provided by the framework.The help entry for this Code Analysis warning says you

shouldn’t ignore it and that it’s a breaking change. This warningholds true for C#, but not for VB. The only downside of this style ofevent declaration is a few extra lines of code of IL in the assembly,which hardly justifies saying you should never suppress the warn-ing. The automatic usage means changing it isn’t a breakingchange. You can suppress the second message globally and justignore warnings about event handlers, but you can’t suppress thefirst globally without missing notification on any other nested pub-lic classes. I think it’s easier to change your delegate declarationsthan to explain why you’re sticking with the old VB style and man-aging the suppressions. VSM

Kathleen Dollard ([email protected]) is a consultant, author, trainerand speaker. She’s been a Microsoft MVP for 10 years and is an activemember of the INETA Speakers Bureau. She wrote “Code Generation inMicrosoft .NET”(Apress,2004), is the founder and principal of GenDot-Net and blogs at http://msmvps.com/blogs/kathleen.

GO ONLINE

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

READ MORE

VS0903AK Read this article online.

You can’t just remove the code with conditionalcompliation because other code is calling the method.

0309vsm_AskKat.36-38.v6 2/19/09 1:27 PM Page 38

Page 41: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VisualStudioMagazine.com · March 2009 · VISUAL STUDIO MAGAZINE 39

Andrew MintzNational Sales ManagerPhone: [email protected]

Chris KourtoglouRegional Sales ManagerPhone: [email protected]

National Accounts DirectorWilliam SmithPhone: [email protected]

Microsoft Account ManagerDanna VedderPhone: [email protected]

West

East

Director, Print ProductionJenny Hernandez-AsandasPhone: 818-734-1520 ext 101Fax: [email protected]

Production CoordinatorSerena BarnesPhone: 818-734-1520 ext [email protected]@1105media.com

Advertising SalesAd Index

Advertiser Page

Atalasoft, Inc 34www.atalasoft.com

ComponentOne 7www.componentone.com

dtSearch Corp. 23www.dtsearch.com

ESRI 5, 27www.esri.com

Intel Corporation C4www.intel.com

LEAD Technologies, Inc. 27, 28, 29www.leadtools.com

MapDotNet 26, 27www.mapdotnet.com

Microsoft Corporation C2,1,15www.microsoft.com

Pegasus Imaging Corporation 27, 30, 31www.pegasusimaging.com

Rally Software 16www.rally.com

Red Gate Software 9www.red-gate.com

Software FX, Inc. 20, 21www.softwarefx.com

Tallcomponents BV C3www.tallcomponents.com

Wayside Technology Group, Inc 2www.waysidetechnology.com

WIBU-SYSTEMS USA, Inc 17www.wibu.com

Edit Ad Index

Altova 11www.altova.com

ComponentOne LLC 14www.componentone.com

Coverity Inc. 10www.coverity.com

Infragistics Inc. 10www.infragistics.com

U2U 14, 16www.u2u.be

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media, Inc., 9121 Oakdale Avenue, Ste. 101,Chatsworth, CA 91311. Periodicals postage paid atChatsworth, CA 91311-9998, and at additional mailingoffices. Complimentary subscriptions are sent to qualifyingsubscribers. Annual subscription rates for non-qualified sub-scribers are: 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: VisualStudio Magazine, P.O. Box 1164, Skokie, IL 60076-8164,email [email protected] or call toll free (888) 768-8759, fax number 847-763-9564. International calls 847-763-9135. POSTMASTER: Send address changes to VisualStudio Magazine, P.O. Box 1164, Skokie, IL 60076-8164.Canada Publications Mail Agreement No: 40612608. ReturnUndeliverable Canadian Addresses to Circulation Dept. orBleuchip 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 prohib-ited except by written permission. Mail requests to"Permissions Editor," c/o Visual Studio Magazine, 2600 ElCamino Real, Ste 300, San Mateo, CA 94403.

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media, Inc. and is distributed with-out any warranty expressed or implied. Implementation oruse of any information contained herein is the reader's soleresponsibility. While the information has been reviewed for

accuracy, there is no guarantee that the same or similarresults may be achieved in all environments. Technical inac-curacies may result from printing errors and/or new develop-ments in the industry.

Corporate AddressCorporate Headquarters: 1105 Media9121 Oakdale Ave. Ste 101, Chatsworth, CA 91311www.1105media.com

Media KitsMedia Kits: Direct your Media Kit requests to Matt Morollo,VP Publishing, 508-532-1418 (phone), 508-875-6622(fax), [email protected]

ReprintsReprints: For single article reprints (in minimum quantities of250-500), e-prints, plaques and posters contact:PARS InternationalPhone: 212-221-9595E-mail: [email protected]/QuickQuote.asp

List RentalThis publication’s subscriber list, as well as other lists from1105 Media, Inc., is available for rental. For more informa-tion, please contact our list manager, Merit Direct. Phone:914-368-1000; E-mail: [email protected];Web: www.meritdirect.com.

Go toVisualStudioMagazine.comto access the stories in thisissue, plus read exclusiveonline-only content.

0309vsm_AdIndex_39 2/19/09 3:44 PM Page 39

Page 42: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

VISUAL STUDIO MAGAZINE · March 2009 · VisualStudioMagazine.com40

THE ART OF THE INTERVIEW

particularly true in development, where technical interviewsimpose unique demands. Here are a few tips for people onboth sides of the interviewing table.

For Interviewees• The most underused answer in technical interviews is,

“I don’t know.” No one knows all the details on today’s plat-forms. Feeling around for the correct answer to a technicalquestion makes you look bad.

• Don’t pad your resume with long lists of technologiesthat you supposedly know. Just because a technology was usedat your company and you got within 10 feet of it doesn’t meanyou know it or should tout it on your resume.

• Bring some sample code, even if the interviewer doesn’task for it. About five or six printed pages will do, and it neednot be a complete program or module. This will impress thepeople you most want to impress. If the interviewer doesn’twant to see it, that tells you something, too.

• Stress the business value of your past contributions to acompany. Most interviewers are a hybrid of business-orientedand technically oriented. If you have that same balance, it willmake you stand out. If you can’t articulate the business value ofyour contributions,you need to take stock of yourself.There aretwo main possibilities: you simply don’t care about the businessside,or your contributions aren’t really very valuable.

For Interviewers• Don’t wing it. If you’re doing any significant amount of

interviewing, you owe it to your company to have a list of ques-tions you can ask, so that you don’t have to think them up on thefly. I have a list of about 40 questions that I mix and match,depending on how the interview goes.(No,you can’t have it.)

• Ask a combination of technical and “soft skill”questions.You need to gauge technical competence, but non-technicalskills such as teamwork, attitude, process knowledge and soforth are at least as important. For example: Suppose a projectsponsor lays out a project to you,and you have loosely estimatedthat it will take at least six months to do it.Then the sponsor says,

“And we’ve promised it to the customer in two months.”Whatdo you do? As Captain Kirk says about the Kobayashi Maru test,there’s no ideal answer. It’s a test of character.

• Ask for sample code. Stress that it need not be a com-plete project, and that you only need to see a few pages. Ibelieve that reading that code will tell you more about a candi-date than any resume they can write. Occasionally, someonewill reply that all of their code is proprietary and they can’tgive you any. You can decide if that’s a dodge, but it’s a clearsignal that the candidate doesn’t do any serious professionaldevelopment outside of work.

• Don’t give the candidate a lot of feedback while they’reanswering questions, especially soft-skill questions. Somecandidates will attempt to feel their way into the answer thatyou want. Keep your body language neutral while candidatesanswer soft-skill questions. If they start going back and forthbetween possible answers, floundering for a response I findacceptable, I scratch them from the list.

• You’ll have many candidates who will be washouts inthe first five minutes. Don’t become abrupt or careless aboutyour treatment of those candidates. It can hurt your organiza-tion’s reputation among other developers.

• When you’re finished asking questions,give the candidatea chance to ask any questions of you. That includes asking youwhy you asked about certain things. They may have beencoached to ask generic questions about the company, but whatyou’re hoping for are deeper questions that reveal generalinquisitiveness.

Again,these tips focus on technical interviews.You can findlists of generic interview tips at sites such as interviewtips.org,and I recommend that you also check those out.VSM

Billy Hollis ([email protected]) is an author, consultant andveteran software developer on Microsoft technologies. He’s currently developing Software as a Service applications withWindows Presentation Foundation and Silverlight and trainingothers on those technologies. Hollis also speaks regularly atVSLive! events.

The Pragmatic Developer

BY BILLY HOLLIS

Whether you’re looking for work or looking to hire,one thing you can’tafford to overlook is the importance of a strong interview.This is

0309vsm_PragDev_40.v2 2/19/09 2:07 PM Page 40

Page 43: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

Project3 1/21/09 11:34 AM Page 1

Page 44: GETTING DIRECTIONS - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_903DG.pdf · GETTING DIRECTIONS.NET developers face adjustments as they start coding for Microsoft’s ... Telerik

EVOLVE YOUR CODE.Parallelism breakthrough.

Accelerate parallelism for multicore with the Intel® Parallel Studio. This one-stop software toolset will change the way you code. Designed for today’s serial apps and tomorrow’s parallel innovators.

Learn more and sign up for Beta: www.intel.com/go/parallel

© 2009, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and other countries. *Other names and brands may be claimed as the property of others.

Project2 2/9/09 11:49 AM Page 1