Вы находитесь на странице: 1из 44

0309vsm.C1.

v1

2/19/09

1:55 PM

Page 1

The Art of the Interview


VisualStudioMagazine.com

E N T E R P R I S E

S O L U T I O N S

F O R

.N E T

D E V E L O P M E N T

GETTING DIRECTIONS
.NET developers face adjustments
as they start coding for Microsofts
high-flying collaboration platform.

Generate Code from


Custom File Formats

MARCH 2009 Vol. 19, No. 3

Create Anonymous Types

Project1

1/21/09

11:14 AM

Page 1

Project1

1/21/09

11:15 AM

Page 2

Project5

1/28/09

2:41 PM

Page 1

Your best source for


software development tools!

LEADTOOLS Document
Imaging v 16:
by LEAD Technologies
LEADTOOLS Document Imaging has every
component you need to develop powerful
image-enabled business applications including
specialized bi-tonal image display and
processing, document clean up, high-speed
scanning, advanced compression (CCITT
G3/G4, JBIG2, MRC, ABC) and more.
Multi-threaded OCR/ICR/OMR/
MICR/Barcodes (1D/2D)
Forms recognition/processing
PDF and PDF/A
Paradise #
L05 03201A01 Annotation (Image Mark-up)
C/C++, .NET, WPF - Win32/64
$
99
programmers.com/lead

2,007.

550.99

CALLI

VDI Included

programmers.com/vmware

by Pragma Systems

The c-treeACE database engine is a high performance


database alternative proven by developers in mission
critical enterprise systems, desktop deployments, and
embedded devices for over 25 years.
Complete set of APIs including ADO.NET, LINQ,
C#, C/C++, ODBC, JDBC, VCL, and dbExpress
Graphical productivity tools
Simple deployment
No DBA or ongoing administration
Low deployment licensing costs
Cross-platform support for all major platforms
including Windows, UNIX, Linux, and Mac OS X

Best
Word Processing Components
Seller!
TX Text Control is royalty-free,
robust and powerful word processing
software in reusable component form.

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
programmers.com/pragma

Worlds #1 selling development spreadsheet


Read/Write native Microsoft Excel Files
Cross-sheet formula referencing
Paradise #
F02 01101A01 Fully extensible models
Royalty-free, run-time free
programmers.com/farpoint

Paradise #
F01 0131

711.

99

Make your applications faster, easier to deploy,


and more affordable with c-treeACE.
programmers.com/faircom

Mindjet MindManager 8
by Mindjet
Do you harness the wealth of data,
Web pages, and other input that comes
your way every day? Is there a way to
use it more effectively to formulate new
ideas, sharpen your focus, and ultimately
drive your success? New MindManager 8
for Windows is the answer.
Unlike the usual linear-based approach of
most productivity tools, MindManager 8
uses mind-mapping technology to let you
capture, organize, and communicate
information using an intuitive visual
canvas. Youll be able to work smarter
and transform your ideas into action
more quickly.

.NET WinForms control for VB.NET and C#


ActiveX for VB6, Delphi, VBScript/HTML, ASP
File formats DOCX, DOC, RTF, HTML, XML, TXT
Professional Edition
PDF export without additional 3rd party
Paradise #
tools or printer drivers
T79 02101A01
Nested tables, headers & footers, text
$
99
frames, bullets, numbered lists, multiple
undo/redo, sections, merge fields
Download a demo today.
Ready-to-use toolbars and dialog boxes

919.

programmers.com/theimagingsource

Enterprise Architect 7.1


Visualize, Document and
New
Control Your Software Project
Release!
by Sparx Systems
Enterprise Architect is a comprehensive,
New
Release!
integrated UML 2.1 modeling suite
providing key benefits at each stage of
system development. Enterprise Architect
7.1 supports UML, SysML, BPMN and
for Windows other open standards to analyze, design,
Corporate Edition
1 User test and construct reliable, well under1-4 Users
Paradise # stood systems. Additional plug-ins are
Paradise #
also available for Zachman Framework,
F15 17301A02
SP6 0001
MODAF, DoDAF and TOGAF, and to
$
99 integrate with Eclipse and Visual Studio
$
99
2005/2008.
programmers.com/mindjet
programmers.com/sparxsystems

299.

182.

SlickEdit 2008
for Windows

Telerik RadControls

Multi-Edit 2008

by Telerik

by Multi Edit Software

by SlickEdit
SlickEdit 2008 is a cross-platform, multi-language code editor that gives programmers the
ability to code in over 40 languages on 7 platforms. This latest version builds on the companys 20 years of experience in enabling developers and development teams to create, navigate, modify, build, and debug code faster and
more accurately.

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 your
ASP.NET projects. The suite takes full advantage
of the features included in Visual Studio 2005.
RadControls for ASP.NET helps developers deliver
feature-rich, standards-compliant (WAI-A, WCAG
1.0, XHTML 1.1) and cross-browser compatible
Single Developer
Web applications, while significantly cutting
Paradise #
their development time. RadControls for ASP.NET
TB3 01101A01
includes: RadEditor, RadTabstrip, RadInput,
RadCalendar, RadUpload, RadWindow, RadAjax,
$
99
RadGrid, RadCombobox, RadMenu, RadSpell,
RadChart, RadTreeview and more.
programmers.com/telerik

Multi-Edit 2008 delivers, a powerful IDE,


with its speed, depth, and support for
over 50 languages. Enhanced search
functions include Perl 5 Regular
Expressions and definable filters.
Supports large DOS/Windows, UNIX,
binary and Mac files. File Sync
Integration for: Delphi 6, 7, 2005,
C++Builder 6, BDS 2006 and RadStudio
2007, VB 6, VC 6, VS 2003 & VS
2005. Includes file compare, code
beautifying, command maps, and
much more.

Paradise #
M39 19201A01
$

949.

View Premier
Paradise #
V55 66101A01

TX Text Control 14

The Best Grid is a Spreadsheet. Give your users


the look, feel, and power of Microsoft Excel,
without needing Excel installed on their machines.
Join the professional developers around the
world who consistently turn to FarPoint Spread
to add powerful, extendable spreadsheet solutions to their COM, ASP.NET, .NET, BizTalk Server
and SharePoint Server applications.

936.99

Bottom line: dtSearch manages a terabyte of


text in a single index and returns results in
$
99
InfoWorld
less than a second.
programmers.com/dtsearch

New
Release!

by FairCom

FarPoint Spread
for Windows Forms

Single Server
Paradise #
D29 02101A07

View Premier is an Enterprise-class


Desktop and Application virtualization
suite that enables you to take control
of your desktops and applications while
providing storage optimization. The
Starter Kit is the entry level solution
that includes 10 concurrent user licenses
of VMware Infrastructure Enterprise,
vCenter Foundation, ThinApp, View
Composer and View Manager. SnS
is required and sold separately.

c-treeACE Professional

Full-featured server, graphical clients and graphical


management capabilities are all included.

Add dtSearchs blazing speeds


(CRN Test Center) searching and
New
file format support
64-bit
Version!
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

Pragma Fortress SSH


Secure Connectivity
Pragma Fortress SSH provides a comprehensive
secure connectivity framework for enterprise
customers.

Paradise #
P35 0439

VMware View Premier


Starter Kit

dtSearch Engine for Win & .NET

615.

242.99
programmers.com/slickedit

800-445-7899
Prices subject to change. Not responsible for typographical errors.

New
Release!
1-49 User
Paradise #
A30 01201A02

161.99

programmers.com/multiedit

programmersparadise.com

0309vsm_TOC_3-4.v4

2/19/09

11:40 AM

Page 3

Contents
March 2009 VOLUME 19 NO. 3

C O LU M N S
C# CORNER

32 Create Anonymous Types


Taking 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 typesincluding whether
they are classes or structs. BY BILL WAGNER

D E PA RT M E N T S

6 Editors Note

BY MICHAEL DESMOND

8 Letters to the Editor


10 First Looks
Product Listings . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

39 Index of Advertisers

12

40 The Pragmatic Developer


The Art of the Interview BY BILLY HOLLIS

F E AT U R E S

12

Getting Directions

32

.NET developers face adjustments as they start coding for


Microsoft's high-flying collaboration platform.
BY MICHAEL DESMOND

18

Generate Code from Custom


File Formats

COVER COMPOSITE IMGAES FROM ISTOCKPHOTO.COM

Create a custom tool to provide a flexible and easy way


to generate code on demand. BY PETER VOGEL

.NET and ASP.NET developers


working with SharePoint must
be ready to do things
the SharePoint way.
Michael Desmond, Getting Directions p. 12

www.visualstudiomagazine.com March 2009 VISUAL STUDIO MAGAZINE

0309vsm_TOC_3-4.v4

2/19/09

11:41 AM

Page 4

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

Online

VisualStudioMagazine.com

Content
LEARN FROM THE PROS
As a developer you are constantly facing the
problem of how to keep up with all the new
technologies being released while still getting your job done. You keep hearing about
solutions to your programming problems but
the question is: are they the right solutions
for your particular needs? You could spend
hours or even days trying to find the
answers yourself, or you could let the
experts do it for you. Redmond Media Group
Events offers a variety of conferences and
shows where you can learn about new technologies and what they might offer you, attend in-depth workshops that
focus on topics specific to your needs, ask questions of the experts, and
interact with your peers to discuss problems they face and what solutions
theyve come up with. Whether its Web design, .NET development, or SQL
Server programming, weve got an event that matches your needs. Visit
RedmondEvents.com to learn more about upcoming conferences and shows.

Classic VB Corner:
Forward Compatibility
Does anyone really expect to be able to take data from
the current version of AppX and use it freely in the
previous version of AppX? Of course not! Karl E. Peterson
discusses forward compatibility and how data assets
simply must move forward from one version of an
application to the next. LOCATOR+ CODE: VS0903KP2

GIVE US YOUR FEEDBACK


We at Visual Studio Magazine and VisualStudioMagazine.com
are constantly trying to improve the content we provide you
and the way that content is presented, both in the pages of
the magazine and online. We value your opinions about any
aspect of the magazine or our Web site. If you have any
comments, criticisms, or suggestions on how we might
improve things please feel free to contact us. You can reach
us by email at vsmedit@1105media.com or go online at
VisualStudioMagazine.com and post your comments.

ONLINE ARTICLES

Practical ASP.NET:
Accessing Connection Strings Reliably
In his ongoing series on ASP.NET, Peter Vogel provides an alternative to
the default mechanism for accessing connection stringand plugs his
next book. LOCATOR+ CODE: VS0903PV1

Practical ASP.NET:
Updating Multiple GridView Rows
Peter Vogel explains how putting updateable controls in the
ItemTemplate in a GridView gives developers what they want: the ability
for users to change more than one row at a time. The cost is writing
some extra code. LOCATOR+ CODE: VS0903PV2

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

ONLINE TUTORIALS

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

What Are Locator+ Codes?


Locator+ codes give you instant access to a feature on Visual
Studio Magazine Online. Simply type the Locator+ code into
the field in the upper-right corner and click on FIND IT.

.NET NEWSLETTER SIGN-UP


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

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Project17

1/19/09

5:24 PM

Page 1

Integrate Mapping and GIS into Your Applications


Give your users an effective way to visualize and analyze their data so they can make more informed
decisions and solve business problems.
By subscribing to the ESRI Developer Network (EDNSM), you have access to the complete ESRI
geographic information system (GIS) software suite for developing and testing applications on
every platform. Whether youre a desktop, mobile, server, or Web developer, EDN provides the
tools you need to quickly and cost-effectively integrate mapping and GIS into your applications.

Subscribe to EDN and leverage the power of GIS to get


more from your data. Visit www.esri.com/edn.
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.

0309vsm_EdNote_6-8.v2

2/19/09

Editors

3:25 PM

Page 6

Note

WHAT HAPPENS NEXT


By now youve no doubt noticed some changes in this months issue
of Visual Studio Magazine.

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

What does it all mean? Quite a lot, actually. The new staff
reflects an expanding mission for VSM. The magazine will
continue to publish cutting-edge tutorial and how-to content, but our coverage will expand to include issue-oriented
features, timely news analysis and incisive commentary.
Developers working with tooling as expansive and as powerful as Visual Studio dont work in a vacuum, and Visual Studio
Magazine will reflect that.
This issue is really the first step in the effort to broaden
the scope and reach of VSM. In April, we plan to unveil
a redesigned publication that is fully aligned with our
expanded vision.
I want to emphasize that Visual Studio Magazine is here
to serve you. With so many big and exciting changes afoot,
were more anxious than ever to hear the opinions and input
of developers and managers. What can we do to improve
VSM? What kinds of stories, content, tutorials and interaction are you looking for? And how can these things be tuned
to help you do your jobs better? We want to hear your ideas
e-mail me at mdesmond@1105media.com.

PHOTO BY IRA WYMAN

Theres a lot going on at VSM as we work to improve the publication, and were anxious to let you know what were up to,
and to hear your opinions about what we might do better.
Its probably best if I start at the top. Back in January our
parent company, 1105 Media Inc., announced that it was
merging its two developer publicationsVSM and the twicemonthly Redmond Developer Newsinto a single, integrated
publication under the title Visual Studio Magazine. The move
blends the best aspects of each magazine, combining VSMs
detailed how-to content and coding tutorials and RDNs indepth analysis of key issues and technologies.
In a sense, RDN and VSM have been two sides of the
same coin. RDN gave developers fair warning of what was
coming, be it new technologies or newly discovered challenges, and VSM showed them how to work with it.
Now these two missions are being united under the VSM
banner. The move reflects the fact that developers need context. They need to know about the tools theyre mastering, so
they can make better decisions on how to use them. To that
end, future issues of VSM will deliver the kind of in-depth
features, timely technology and product news, plus expert
insight that youve seen in RDN since 2006.
The transition brings significant changes to the VSM
staff. I want to take a moment to recognize the outstanding
efforts of former VSM Editor in Chief Patrick Meader and
Managing Editor Guy Wright, who are both moving on from
VSM as part of the transition. Ive worked on occasion with
Patrick over the past two years, and Ive respected him deeply
for his intelligence, composure and commitment to principle. Patrick is as dedicated and forthright a person as Ive ever
run across in my 16 years in IT publishing, and his success
over the years at VSM is testament to that.
Joining the VSM team are three new faces. Kathleen
Richards is the new executive editor and will guide many of
the key how-to departments and features at the magazine.
Richards was senior editor at RDN and before that at Application Development Trends magazine. Jeffrey Schwartz
arrives as news editor, where hell drive the front-of-the-book
news and review content. Schwartz comes to VSM from RDN,
where he managed the books large news section. Prior to that
he was a senior editor at VAR Business.
As for myself, Ive moved over as editor in chief of RDN
to serve as editor in chief of VSM.

BY MICHAEL DESMOND
editor in chief

Project7

2/10/09

3:39 PM

Page 1

STUDIO FOR SILVERLIGHT


STOCK PORTFOLIO DEMO

STUDIO FOR IPHONE


CTP NOW AVAILABLE

Studio for Silverlight


Produce 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 unique


controls like animated GIFs, spell-checking, file uploader,
and more
Increase functionality with a small footprint: average
control size of 77KB (XAP size) eliminates the need to worry
about adding to the size of the download
Access the best resources: 15+ samples with source code
for quick learning

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

Studio Enterprise 2008 v3 delivers


exactly what you need to produce
next-generation UIs for the Web.

Studio for ASP.NET


AJAX-enabled controls for desktop-like experience on the Web
Build lightweight, high-performance Web apps: 3x
smaller footprint, 10x faster performance
Style and animate your Web UI without coding: dozens
of built-in visual styles & animation effects

Studio for iPhone


Build 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 familiar


ASP.NET Framework

GET STARTED TODAY DOWNLOAD YOUR FREE TRIAL at

www.componentone.com/amazingweb

Grids Charting Reporting Scheduling Menus and Toolbars Ribbon Data Input Editors PDF
WinForms WPF ASP.NET Silverlight iPhone Mobile ActiveX

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. All
product and brand names are trademarks and/or registered trademarks of their respective holders.

0309vsm_Letters_8.v3

2/19/09

2:47 PM

Page 8

Letters
Letters to Visual Studio Magazine are
welcome. Letters must include your
name, address and daytime phone
number to be considered for publication. Letters might be edited for form,
fit and style. Letters express the views
of the individual authors, and do not
necessarily reflect the views of the
editors, VSM or 1105 Media. Please
send them to Letters to the Editor, c/o
VSM, 16261 Laguna Canyon Road
Ste. 130 Irvine, Calif. 92618; fax
them to 949-265-1528; or e-mail
them to vsmedit@1105media.com.

Agile Arguments

illy Hollis The Pragmatic Developer column (Is Agile Rock or Disco? January
2009) 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 not
a process. Truly Agile development is adaptable, and therefore it can work with nonseasoned developers.
Ted Malone,
Colorado Springs, Colo.

VisualStudioMagazine.com
March 2009 Volume 19 No. 3
Editorial Staff
Vice President, Doug Barney
Editorial Director
Editor in Chief

Michael Desmond

Executive Editor

Kathleen Richards

News 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 Media
Editor, VisualStudio Becky Nagel
Magazine.com
Executive Editor, New Media
Online News Editor
Associate Editor, Web
Web Producer

WF: Change for the Worse?


I suppose out of all the possible changes that might trouble me in Windows Workflow
Foundation (WF) 4.0as discussed by Kathleen Dollard in her Ask Kathleen column
(Windows Workflow Changes Direction, January 2009)the loss of the code activity is the
most upsetting. This makes the possibility of making lightweight WF activities that accomplish relatively simple tasks more difficult than necessary. By removing this piece of functionality, Microsoft has effectively shackled the developer to creating activity libraries. While that
has 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 of
workflows is a good thing. Performance improvements are great, but performance improvements that cause the loss of very useful functionality are just wrong.
Marcelo Lopez, Jr.,
Florida

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Michael Domingo
Kurt Mackie
Gladys Rama
Shane Lee

Director, Web Development

Rita Zurcher

President

Henry Allain

Vice President, Publishing


Director of Marketing
Online Marketing Director

Id like to further a point Hollis made in his article: Its hard to do any development without
good 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 to
encourage the rest to find a more suitable field in which to work.
The so-called software crisisa shortage of good developers compared to the amount
of software that needs to be writtenis an issue of supply and demand. Theres an inherent
undersupply of good developers, but theres also an oversupply of demand as many clients
just want variations on the same thing. If its more profitable to be a good developer, those
good developers will also create frameworks and tools to help address the demand-side problems as well.
Anonymous,
Posted online

Jeffrey Schwartz

Managing Editor

President &
Chief Executive Officer
Senior Vice President
& Chief Financial Officer
Executive Vice President

Matt N. Morollo
Michele Imgrund
Tracy S. Cook

Neal Vitale
Richard Vitale
Michael J. Valenti

President, 1105 Events

Dick Blouin

Vice President, Finance


& Administration

Christopher M. Coates

Vice President, Digital Media,


Audience Development

Abraham M. Langer

Vice President, Information


Technology & Web Operations

Erik A. Lindgren

Vice President, Digital Media,


Advertising

Doug Mashkuri

Vice President,
Attendee Marketing
Chairman of the Board

Carmel McDonagh

Jeffrey S. Klein

REACHING THE EDITORS


Editors can be reached via e-mail, fax, telephone or mail.
A list of editors and contact information is available at
VisualStudioMagazine.com.
E-mail: E-mail is routed to individuals desktops. Please use the
following form: FirstnameinitialLastname@1105media.com.
Do not include a middle name or middle initials.
Telephone: The switchboard is open weekdays 8:30 a.m.
to 5:30 p.m. Pacific Time. After 5:30 p.m. you will be directed
to individual extensions.
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 Magazine
The opinions expressed within the articles and other contents
herein do not necessarily express those of the publisher.

Project2

2/11/09

11:06 AM

Page 1

How to boost the performance of your


.NET applications with ANTS Proler
Performance is crucial, so here are some tips to make sure
that your applications run efciently.

or maximum efciency, follow our


three proling tips outlined below.

1. Prole your .NET code


A code proler is an essential
tool to have in your development
toolkit. Although manual logging
can sometimes help, it is often
impossible to nd performance
bottlenecks without a code proler.
A proling tool takes the guesswork
out of performance analysis and
drastically reduces the amount of
time taken to nd problem code.

2. Quickly locate your


performance bottleneck
Run ANTS Proler Pro to obtain
detailed quantitative data that will
help you identify inefcient resource
usage. ANTS Proler gives you hit
count and line-level timings, so you
can quickly identify the specic
lines of code which are affecting the

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

3. Optimize efciently
Now 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.

performance of your application.


No time wasting. No guessing.
Use real data instead!

"ANTS Proler took us


straight to the specic areas
of our code which were the
cause of our performance
issues."
Terry Phillips Sr. Developer,
Harley-Davidson Dealer Systems

"We were able to improve


performance in parts of
the application up to 10 times,
and our customer noticed the
results. A powerful, instantly
understandable proler.
Highly recommended."
Dan Ports Lead Developer, Intrigma Inc

ANTS Proler shows you line-level timings, so you can drill down to the specic lines of code responsible
for performance inefciencies.

Download your 14-day, fully functional


free trial from www.red-gate.com

0309vsm_FirstLooks_8-9.v5

2/19/09

12:18 PM

Page 10

First
PRODUCT LISTINGS

Looks

REVIEWS

Coverity Prevent and Quince UX


Patterns Explorer

Coverity Prevent
Coverity Inc. has improved the support for managed and native code in its static-analysis software. With Coverity Prevent, developers can
automatically scan and analyze C#, C, C++ and
Java source code on their desktops or on the
build server. Its one of the few static-analysis
tools that supports both Visual Studio and
Eclipse integrated dev environments.
The product ships with a Web server, which
connects to the help desk or Active Directory
server on your network and a back-end database. Developers open the Coverity browser
and log on to the Web service. Prevent builds
the source code, analyzes it based on selected
quality and concurrency checkers, and then
commits the results to the database. A buildutility wrapper wraps around the build but
doesnt change it. Depending on the number of
checkers, the build and analysis typically take
three to five times the normal build time.
After a run, developers can view a breakdown of the code base in the browser: how
many files and lines of code, the number of new
defects since the last Run ID, and outstanding
defects that still need to be inspected and classified. Developers cant edit the code from within the Prevent interface, however.
The latest version beefs up VS integration,
enabling developers to perform static analysis from within VS 2005 and VS 2008. The
company has also added support for Windows
Vista, Windows Mobile, Windows Automotive
and Xbox.
In addition, Coverity has extended Prevents C# functionality with new quality and
concurrency checkers. Prevent is the first
product to support C# concurrency testing for
issues such as deadlocks and race conditions,
according to the company. With this upgrade,

10

it also now offers concurrency modeling to


help developers find critical defects in multithreaded Win32 apps.
Prevent is the flagship product in Coveritys
Software Integrity Suite, and the only product
that currently supports C#. Upcoming staticanalysis tooling will take advantage of
Microsofts efforts to put annotations into its
system header files.

format on various platforms, including


ASP.NET, Windows Forms and PHP. Developers can search Quince for commonly used patterns based on end user tasks, wireframe map
locations and tags. The patterns catalog is set
up so that the community can comment on
patterns and their experiences in real time.
The patterns are aggregated based on community feedback.

Coverity Prevent
Coverity Inc.
Price: Contact vendor for pricing
Web: www.coverity.com
Phone: 800-873-8193;
415-321-5237

Quince UX
Patterns Explorer
Components vendor Infragistics
Inc. has launched a unique Silverlight 2 application called
Quince UX Patterns Explorer.
The app offers developers a
resource for best practices in
user experience design and user interface
patterns. With Quince, developers can hone
their UI design skills with guidance from the
community-driven catalog by seeing what patterns other practitioners have used and by
viewing developer feedback. Developers can
also share and upload their own UI patterns.
Quince offers guidance on common patterns
for complex data entry, label alignment and
navigation, among other UI tasks. The library is
initially based on tools and practices that the
20-year-old company uses internally, as well
as expertise garnered from industry sources.
Quince aggregates close to 100 patterns
and shows implementations via a carousel

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Yahoo! Inc. and Google Inc. offer pattern


libraries, but there isnt a de facto resource in
the .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

Editors 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: vsmedit@1105media.com.

0309vsm_FirstLooks_8-9.v5

2/19/09

PRODUCT LISTINGS

12:18 PM

Page 11

REVIEWS

Altova MissionKit Boasts XBRL Savvy


If you handle enterprise-level business intelligence (BI) and financial reporting, it wont be long
before the front office summons you to deal with
eXtensible Business Reporting Language (XBRL).
XBRL is an XML vocabulary for exchanging business and financial data. Its a standard for
machine-to-machine reporting thats been adopted by the U.S. Securities and Exchange Commission (SEC) and European authorities.
Altova, well known for its leadership in all
things XML, has updated its products to support
XBRL and bundled them into MissionKit 2009 for
Enterprise Software Architects. The goal is to give
you the tools (but not necessarily the training) to
deliver reports compliant with the International
Financial Reporting Standards (IFRS).
For XBRL beginners, it would have been ideal to
have a hands-on walkthrough that starts with a
financial database and ends with a valid XBRL docPRODUCE READABLE FINANCIAL DOCUMENTS USING XSLT
ument ready for submission to authorities. Alas,
STYLESHEETS. StyleVision, a member of Altovas MissionKit 2009
theres no XBRL For Dummies manual included. suite, lets you design human-readable documents from machine-toWhile each application includes tantalizing tidbits machine files in XBRL format. The output options include HTML, RTF,
on working with XBRL, I felt like I was solving a jig- PDF and Word 2007.
saw puzzle without seeing the entire picture first.
XBRL is the buzz in Altovas all-in-one suite, but dont overlights the location. The other day, I fed XML Spy an XML file conlook the features that have long made the individual compotaining Expression Encoder ScriptCommands. XML Spy generatnents the premier development environment in the XML space.
ed a schema for it in an instant. Be careful what you ask for when
Its hard to beat XML Spy as an all-round markup editor, validator
converting an entire database into XML, though. I ended up with
and XPath query designer. Its Grid view is especially useful for
234 files while searching in vain for XML Spys cancel button.
collapsing and exploring very large documents. As you work, the
MapForce is Altovas flexible tool for mapping and filtering
Messages pane reports errors, explains the problem and highdata graphically from one source to another. The source or target can be a database, .EDI document, Web service, Excel 2007
spreadsheet or a lowly .CSV file. MapForce will generate the C#
AT A GLANCE
classes you might need to automate data conversions.
The third major component, StyleVision, lets you design XLST
MissionKit 2009 for Enterprise Software Architects
templates into which you pour data for human consumption. If
Altova
youre getting into XBRL, be sure to explore the quarterly report
Web: www.altova.com
Phone: 978-816-1600
sample and the Word 2007 preview to see the richness of its
Price: $1,739
output.
Quick Facts: Integrated bundle of XML, database, XSLT
One issue I encountered with MissionKit 2009 was previewdesigner, validation, and publishing tools with added
ing
a stylesheet as a PDF. Even though I had chosen a full instalemphasis on financial reporting support.
lation, StyleVision strangely prompted me for a 19MB download
Pros: Handles all popular and emerging XML-based
technologies including the XBRL-compliance standard;
of the Apache (Java) Formatting Objects processor. Even with
extensive online documentation and Web-based
that in place, the PDF document still failed to appear. I would
support; many examples.
expect Altovas setup kit to automatically install the rendering
Cons: Needs end-to-end walkthrough on producing
engine and tell its PDF module where to find it. VSM
XBRL reports; rendering engine for previewing PDF
documents not fully installed.

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


ASP.NET 3.5 for Dummies (Wiley).

VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

11

0309vsm_F1Sharepoint_12-17.v7

F E AT U R E

2/19/09

4:35 PM

Page 12

SHAREPOINT

Getting Directions

COMPOSITE IMAGES FROM ISTOCKPHOTO.COM

.NET developers face adjustments as they start coding for


Microsofts high-flying workflow and collaboration platform
BY MICHAEL DESMOND

12

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

0309vsm_F1Sharepoint_12-17.v7

2/19/09

4:35 PM

Page 13

SHAREPOINT

imes are tough all over,but it seems somebody forgot to tell that to
the growing ranks of SharePoint developers. Even as general IT
and development budgets turn south, industry watchers say
the amount of activity around SharePoint applications and features
continues to rise.

Behind the activity is the wildfire growth


of Microsofts file sharing, collaboration and
portal platform, which includes Microsoft Office
SharePoint Server (MOSS) 2007 and Windows
SharePoint Services (WSS) 3.0 integrated into
Windows Server.Last year,the SharePoint business
unit surpassed 100 million licenses and $1 billion
in total revenue, according to Microsoft. Now
organizations are looking to leverage those investments by adding custom functionality and applications to their SharePoint infrastructure.
That trend is producing its share of growing
pains, as .NET dev shops contend with SharePoints unique demands and uneven tooling. At
Microsofts TechEd Conference in June 2008,
Chairman Bill Gates admitted during his keynote
Q&A that the company had been caught flatfooted by the amount of development activity
around SharePoint. At the time, he said Microsoft
was working to make SharePoint developers firstclass citizens.
Since then, Microsoft has released the free
Visual Studio 2008 extensions for SharePoint,
which provides Visual Studio project templates for
building, debugging and deploying SharePoint
projects and applications.The January community
technology preview (CTP) of Visual Studio 2008
Extensions for Windows SharePoint Services 1.3
adds 64-bit support, refactoring support for
renaming Web parts, and a command-line interface for enabling continuous integration and build.
The final version is likely due in April, says Paul
Andrew, Microsoft technical product manager for
the 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 will
fully integrate SharePoint development support.
Making the Transition
Evidence of the effort to scale up guidance is
evident in Web sites like Microsofts SharePoint
Developer portal (http://tinyurl .com/bsx8k9)
and the MSDN-hosted SharePoint Server (http://

tinyurl.com/67e7gk) and Windows SharePoint


Services (http:// tinyurl.com/7typk6) Developer
Centers. The sites offer step-by-step tutorials,
design patterns, best practices and other
resources for developers working with the
platform.
Still, challenges remain. Veteran SharePoint
developers complain that a lot of critical insight
and guidance remains scattered among dozens of
individual blogs and SharePoint-themed sites.
My Google reader is filled with stuff I need
to check on, but its all scattershot, says Rutherford Wilson, director of product management for
Atalasoft Inc., an ISV that in February released
Vizit SP, an image-viewing application for MOSS
and WSS environments.There are books, blogs,
and thats about it.
Ryan Thomas, director of the SharePoint
practice at consultancy Syrinx Consulting Corp.,
says developers new to SharePoint are best served
by simply wading into the environment.
The first thing I would do is build a Web
part. Build and have Hello World working in 30
minutes. Then download the SDK and the object
model. If youre going to be a developer, understand the object model and learn how to write
code, he says.
Thomas advises developers to visit the
Microsoft CodePlex site to examine open source
SharePoint projects similar to their own.
He warns that seasoned .NET developers
may find the dynamics around SharePoint development to be quite different from traditional
.NET development. He says SharePoint projects
tend to be client-facing, involving frequent and
intense interaction with business stakeholders.
Theres a good deal of expectation setting that
must be addressed, in part because these users are
often familiar enough with SharePoint to expect
quick results.
VPs, CIOs, business peoplethey just
dont understand the concept of,three weeks and
come back with code, Thomas says. Its very
important to talk to them.

VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

13

0309vsm_F1Sharepoint_12-17.v7

2/19/09

4:35 PM

Page 14

SHAREPOINT

Tale of the Tools


One of the enduring complaints about
SharePoint development has centered around
tooling. That situation is now changing,
thanks in large part to the release of the Visual
Studio extensions for SharePoint and useful
utilities like the SPDisposeCheck tool for
releasing unused memory. Still, major gaps
remain in the SharePoint developer chain.
The extensions are weak, in my opinion, writes Spencer Harbar, a U.K.-based
independent SharePoint developer and
frequent speaker at Microsoft conferences,
in an e-mail interview. At best the extensions are a Band-Aid to bridge the gap
between where we are now, and the future of
SharePoint dev tools.
Harbar says the extensions fall short
for enterprise development, which can
expose weaknesses and flaws in the tooling.
He adds that the integrated SharePoint tooling in Visual Studio 2010 (VS10) should be
much better. I cannot speak much to the
VS10 tools without breaking NDAs, but I
have complete confidence that they will
offer a huge step change in terms of developer tools for SharePoint, he says.
Another issue is the fact that SharePoint environments must run on Windows
Servera nagging issue for developers who
prefer to code on their Windows XP or Vista
workstations. Microsofts Andrew says
developers today have two choices: Either
run Visual Studio on the same Windows
Server OS that hosts SharePoint, or stand up
a virtual machine that incorporates Windows Server and the target SharePoint environment. Most shops, he says, opt for the
latter solution.
Leading component maker ComponentOne LLC is among them. The company
in January released CTP versions of its
SharePoint Web Parts line, which include
map, chart and datagrid controls for SharePoint environments.
You need to make sure you have access
to a testing environment that is not your
development machines, thats particularly
important for SharePoint, says Dan Beall,
product manager for ComponentOne.
Sometimes you have to use remote debugging. Its not as fluid as debugging on a target
machine, but one thing you can do is you can
have your code write entries to SharePoint log

14

THE SHAREPOINT TOOLBOX


harePoint provides an enormous amount of
functionality but can be challenging for new
developers trying to deploy solutions to a
server. Fortunately, there are several free Microsoft
and third-party tools that can be used to create Web parts, site definitions, event
receivers and more. Heres a quick rundown of a few timesaving tools that can
significantly increase your productivity when building SharePoint applications.

WSPBuilder
WSPBuilder provides a nice way to build manifest.xml, .DDF and .WSP solution files
quickly 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 to
deploy a solution. It can be downloaded from www.codeplex.com/wspbuilder.
STSDev
STSDev can be used to build different SharePoint components such as Web parts and
features more easily. Once a project type is selected (note that C# is currently the
only supported language), it will create a VS 2005 or 2008 project automatically
with the necessary SharePoint files and folder structure. STSDev can be downloaded from www.codeplex.com/STSDev.
CAML Query Builder
Collaborative Application Markup Language (CAML) can be challenging to build from
scratch. Fortunately, U2U has released a free tool called CAML Query Builder that can
be used to build CAML queries visually without having to know a lot about CAML. It
will 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 Editor
The Business Data Catalog (BDC) allows external data to be integrated into SharePoint that can be bound to built-in MOSS Web Parts or custom controls. To use BDC
functionality you create custom .XML metadata files that define connection information, queries to execute, plus much more. Although the tool isnt as flexible to work
with as some of the other tools out there, the price cant be beat. Its part of SharePoint 2007s SDK 1.2 release. Read more about it at http://tinyurl.com/cpot8a.
Visual Studio Extensions for SharePoint
Microsoft has released extensions for VS 2005 and 2008 that can simplify the
process of building and deploying List items, Web Parts, Site Definitions and more. At
press time version 1.3 for VS 2008 was released as a community technology preview. Additional information can be found at http://tinyurl.com/9qo9s8.
SPDisposeCheck
Unwary SharePoint developers can easily run into a situation where COM-based
memory doesnt get released by CLR garbage collection. The resulting memory leakage can cripple performance and cause unexpected crashes and failures. The
Microsoft SharePoint Dispose Checker Tool, known as SPDisposeCheck, analyzes
custom compiled assemblies so developers can ensure proper disposal of unused
resources. Check it out here: http://tinyurl.com/dhn69w.
Dan Wahlin

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Project2

2/17/09

3:16 PM

Page 1

0309vsm_F1Sharepoint_12-17.v7

2/19/09

4:35 PM

Page 16

SHAREPOINT

Theres a lot of features in WSS that Microsoft doesnt


really advertise to the rest of the world.
Anne Thomas Manes, Vice President and Research Director, Burton Group

files. There are a couple of freeware tools for looking at whats in the
log files.
SharePoint developers have come to rely on a growing collection
of freely available tools and utilities to help them address the extended
tool chain. Microsoft utilities, like the SPDisposeCheck tool, help
stamp out troubling memory leakage conditions that can occur with
unmanaged component code, while the CAML Query Builder eases
the learning curve around SharePoints Collaborative Application
Markup Language (CAML). The result: Many dev shops have assembled ad hoc tool chains to address the unique demands of SharePoint
coding. (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 working
with SharePoint must be ready to do things the SharePoint way,

says Anne Thomas Manes, vice president and research director at


Burton Group.
SharePoint presupposes a bunch of design patterns and you
kind of have to build your application around those design patterns, she says. And if you want your own design pattern, its
probably not worth the time and effort. Dont attempt to force
fit other design patterns into it, because it will just be a very frustrating experience.
Andrew draws a parallel with ASP.NET programming projects, where developers typically start off by building a framework to
address 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 developer, they already know that framework, they dont have to learn a
new framework, he says.
The problem is that the SharePoint framework is so large that

8ji9Zk8dhih###L^i]dji8jii^c\=ZVYh#
]``\
XYe`
:e|de`f
R_U
ceVR^
f
`
j

e
R
deRj
Y`f]U
d

`
Y
h
X`
UVTZUV
Y`f]U
d

`
Y
R_Uh

GVaanhXjhidbZghVgZegdkZcidWZ*%[VhiZgidbVg`Zi
VcY'*bdgZegdYjXi^kZ!hdndjXVcVkd^YXjii^c\]ZVYh#
EajhGVaan^hi]Zdcan6eea^XVi^dcA^[ZXnXaZBVcV\ZbZciegdk^YZg
idZchjgZndjg6\^aZhjXXZhhl^i]VbdcZn"WVX`\jVgVciZZ#
B[Whdceh[WXekjekh=kWhWdj[[ZIkYY[iiFhe]hWcWjmmm$hWbboZ[l$Yec
' %%.GVaanHd[ilVgZ9ZkZadebZci8dge

16

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

0309vsm_F1Sharepoint_12-17.v7

2/19/09

4:35 PM

Page 17

SHAREPOINT

developers often create custom code for features that are already
there. Harbar urges developers to look carefully before concluding
that a custom Web part or application is necessary.
Easily the most common mistake is not having a core understanding of the product architecture and therefore choosing the
wrong approach to meet specific business requirements.SharePoint is
such a huge platform that its incredibly easy to start implementing
custom code for a task that SharePoint does,Harbar writes.
He adds that developers often make the mistake of assuming
that SharePoint is just .NET, when in fact .NET developers face a
significant ramp in mastering SharePoint dev projects.
Even within the SharePoint family there are choices to be
made. Manes says that many enterprises today opt to develop for
SharePoint Server, when they could achieve similar results and
enjoy a more manageable environment by deploying logic to
Windows SharePoint Services (WSS) instead. She says organizations often concludewronglythat WSS lacks the features they
need to support workflow, coordination, scheduling and other
common business processes.
There are a lot of features in WSS that Microsoft doesnt
really advertise to the rest of the world, Manes says. I can use a
Java portlet and have that be the interface into WSS, because that

works through the Web services interface as opposed to the .NET


interface.
Ultimately, Microsofts Andrew says that .NET developers
must learn to unlearn some of their old assumptions when moving
to SharePoint.
One of issues is people taking the approachand this happens
because projects need to be done fastthat their .NET experience
will get them through their SharePoint project,Andrew says.They
do have to learn new skills. VSM
Michael Desmond (mdesmond@1105media.com) is editor in chief of
Visual Studio Magazine.
GO ONLINE
Use this Locator+ code at VisualStudioMagazine.com to go directly to these
related resources.
READ
VS0903MD Read this article online, which includes more information about
how SharePoint adoption is raising data-management concerns; plus a Q&A
with SharePoint development trainer and VSM online columnist Dan Wahlin.

PERFECTION IN SOFTWARE PROTECTION

Exceptional Software Protection

Software Protection
Document Protection

Order your Free Software Development Kit now!


Phone 1-800-6-GO-WIBU | order@wibu.us

Access Protection
Media Protection

CodeMeter for .NET


3

More than 1000 Key-Storage License Entries

- Different ISVs can share one dongle


3

Secure Expiration Date with a Real-Time-Clock

- Unique Time Certication Feature


- Control Relative and/or Absolute time
3
3

More ways to sell = More sales


Create Student and Version Licenses

Control Network
etwork Licensing

- Control concurrent users


- Control roaming users
3

Create Standby Licenses

- Hot Standby and Cold Standby


- Provide Overow Licenses
3

Pay-Per-Use Counter

WIBU-SYSTEMS USA Inc.


110 W Dayton Street,
Edmonds, WA 98020
United States
www.wibu.us
info@wibu.us

VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

17

0309vsm_F2HowTo_16-23.v7

F E AT U R E

2/19/09

12:33 PM

Page 18

B U I L D I N G C U S TO M TO O LS

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

VB.NET
C#
SQL Server
ASP.NET
XML
Other:

18

Youre already using a custom tool every


time you add a dataset to an application. VS sets
the CustomTool property of the datasets .XSD to
MSDataSetGenerator. Whenever you close the
.XSD fileor, in Visual Studio 2008 (VS 2008),
whenever you switch away from the fileVS
passes MSDataSetGenerator the contents of the
.XSD file, which MSDataSetGenerator then converts to code for the .XSDs code file and hands
back to Visual Studio.
You can design your own input format and
write your own custom tool to generate code for
you. Once you build your custom tool, you simply
have to enter its name in the CustomTool property

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

of the file with your input. VS takes care of the


rest (see Figure 1, opposite page).
Using a tool to generate repetitive code
ensures consistency and reliability. It guarantees
that your code generates the same way every
time, reducing the amount of testing you have to
do. Using a custom tool can also make you more
productive, provided that entering the specifications is faster than writing the code. If you decide
you need to enhance your generated code, just
modify your custom tool to incorporate your
insights.Your class will be regenerated automatically with the new version of the code the next
time you build your project.

ILLUSTRATION FROM ISTOCKPHOTO.COM

TECHNOLOGY TOOLBOX

oure writing the same code over and over again with only
minor changes, and youre about to do it again. Stop. If youre
creating a standalone class (either a class that youll call from
your applications code or a class that you can inherit from),build a custom
tool that writes the code for you now and every time youll need it.

0309vsm_F2HowTo_16-23.v7

2/19/09

12:33 PM

Page 19

B U I L D I N G C U S TO M TO O LS

Using a tool to generate repetitive code

ensures consistency and reliability.


Installing to the GAC Automatically
Creating a custom tool (also called a single file generator) presents one problem. VS is a Windows application that calls a custom
tool directly, so your custom tool must integrate with Windows and
COM.You can create your custom tool in .NET, but you must make
your 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). This
means you must give your DLL a strong name. The good news is
that you can configure VS so that all of these operations happen
every time you compile your application. More good news: Most of
the support for creating a custom tool is boilerplate and is identical
from one custom tool to another.You only have to write it once and
then copy and paste it to any other tool you create.
You can build a custom tool in a variety of ways. I use the
Microsoft.VisualStudio.Shell.Interop.IVsSingleFileGenerator and
Microsoft.VisualStudio.OLE.Interop.IObjectWithSite interfaces. To
create a custom tool,begin by creating a class library in the language of
your choice and then add to it references to the Microsoft.VisualStudio.OLE.Interop and Microsoft.VisualStudio.Shell.Interop libraries.

FIGURE 1 Code-Generation Output The CodeGenerationInput.xml


file 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 CodeGenerationInput.Generated.cs file.

Next, configure your project to have VS call the gacutil utility to


put your DLL in the GAC after your application compiles. First, find
the full path to wherever gacutil.exe is installed on your computer. In
VS,open the Project Properties for your application.If youre working
in Visual Basic, select the Compile tab and click on the Build Events
button. If youre working in C#, simply select the Build Events tab.
Add these lines to the PostBuild event textbox (replace <full path to
gacutil> 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 any
existing version of your tool from the GAC. The second line (which
uses the TargetPath parameter) installs the current version of your
tool into the GAC.
When I build a project, I sometimes get an error message that
states Microsoft.VisualStudio.Shell.Interop is not registered for
COM interop.This doesnt stop the project from building or interfere with the custom tool executing, so if you get that message,
ignore it. However, to ensure that the PostBuild event script executes every time you recompile your DLL, set the dropdown list
underneath the PostBuild textbox to When the build updates the
project output.
To install your project in the GAC successfully, you must generate an .SNK file that holds a digital signature (a strong name). Go
to the Signing tab and check the Sign the assembly option. From
the dropdown list you just enabled, select <New> to display the
Create a Strong Name Key dialog. Enter a valid file name in the Key
file nametextbox. The resulting file can be read with Notepad, so if
you want to ensure that no one but you has access to the file, enter a
password in the dialog; if youre not worried about that, then
uncheck the password option before clicking on the OK button.
Integrating with Windows and COM
The next step is to configure your project to have your DLL registered with COM/Windows every time you build it. Still in Project
Properties, find the Register for COM interop checkbox on the
Build tab (for C#) or Compile tab (for Visual Basic) and check it.
Youll need to revisit this option if you change the projects configuration setting (for example, if you switch from Debug to Release),
because the option is cleared when the configuration changes. As
part of supporting COM, you also must go to the Application tab
and click on the Assembly Information button. Check the Make
assembly COM-Visible option on the resulting dialog.
Your custom tool must implement two interfaces: IVsSingleFileGenerator and IObjectWithSite. You must assign your class a
unique GUID to identify it to Windows. Simply add a System.Runtime.InteropServices.Guid attribute to your class and pass it a

VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

19

Project5

12/11/08

4:42 PM

Page 1

BeTheDataGuru

Visual Studio

WPF/Silverlight

SharePoint

SQL Server

Java

COM

PowerShell

Project5

12/11/08

4:43 PM

Page 2

Achieve AHigher State Of DataVisualization


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 to
enterprise developers working with diverse markets, platforms and environments. This
wisdom has evolved into a vast body of products, including a data presentation tool that
provides a best-of-breed solution for Windows developers seeking enterprise quality and
performance, as well as a professional IT monitoring solution offering incredible features for
reporting and monitoring data. For a world of data visualization products that can raise your
work to a higher level, depend on the source thats clearly on top.
Our most popular product, Chart FX provides
charts, gauges and maps with additional vertical
visualization functionality for business intelligence
(OLAP), geographic data, financial technical
analysis, and statistical studies and
formulas. Recognized as the innovator
and leader of the charting component
category for the past 15 years, Chart FX
delivers incomparable gallery options,
aesthetics and data analysis features.
Grid FX was specifically designed for visual studio
developers to take advantage of a powerful
design-time experience, integrated Chart FX
functionality right in the box, and AJAX to
provide robust, run-time functionality in ASP.net
applications. The dynamic aesthetic features
for data presentation and analysis allow simple
adaptation to an existing application or to specific
corporate branding guidelines.
PowerGadgets puts powerful IT monitoring
on your desktop and in your data sidebar.
IT professionals can now create gadgets
that consume data from WMI, Exchange,
SQL Server and even the Windows Registry.
PowerGadgets does not require any
development environments, servers or
browsers to run real-time gadget components
such as charts, gauges and maps.

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

Data visualization for every need, every platform

0309vsm_F2HowTo_16-23.v7

2/19/09

12:33 PM

Page 22

B U I L D I N G C U S TO M TO O LS

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.

GUID. In VS 2008, you can generate a GUID by selecting Create


GUID from the Tools menu. In VS 2005, open the VS Command
window and run the guidgen utility. Both methods open the Create
GUID dialog. Regardless of how you start the tool, pick option 4 to
generate a GUID compatible with the Guid attribute (the result will
be enclosed in braces that youll need to delete after pasting the
GUID into your code).
Once youre done, your class declaration will look like this in
Visual Basic:

Public Shared Sub RegisterClass(ByVal typ As Type)


Dim key As Microsoft.Win32.RegistryKey
key = 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.Guid( _
"B2429B91-452D-4a95-A355-435337729EFB")> _

<System.Runtime.InteropServices.ComUnregisterFunction> +

Public Class TextGenerator

Public Shared Sub UnregisterClass(ByVal type As Type)

Implements _

Microsoft.Win32.Registry.LocalMachine.DeleteSubKey( _

Microsoft.VisualStudio.Shell.Interop. _

"SOFTWARE\Microsoft\VisualStudio\" & VSVersion & _

IVsSingleFileGenerator

"\Generators\" & CSLangGUID & "\" & ToolName & "\", _


False)

Implements Microsoft.VisualStudio.OLE.Interop. _
IObjectWithSite

For VS to know about your custom tool, you need to add at least one
key to the Windows registry. The easiest way to do this is to add two
methods to your application: one to add the key and one to delete it.
With the right attributes on those methods, they will be called automatically when your custom tool is registered or deregistered with
Windows. (The changes you make to your project ensure that your
tool is registered and deregistered each time you build it.)
The code in these two methods is mostlybut not completely
boilerplate.You need to specify the version of VS that the custom tool
works with,provide a GUID that identifies the language of the projects
that your tool will work with, provide the name youll use in the CustomTools property and give a description. In addition, you have to
copy the GUID you generated for the GUID attribute into this code.
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. This VB code creates a tool for
C# projects in VS 2008 called TextGenerator:

End Sub

If you want to support more than one language (for instance, if


your tool works equally well in both C# and VB projects), just write
out two keys: one for each language. The language GUID to use for
VB is 164B10B9-B200-11D0-8C61-00A0C91E29D5.
Using Standard Code
For the four methods required by the interfaces your class has to
implement, you can use the same code for every custom tool you
create. For example, the code for the GetSite and SetSite methods
never 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

Shared VSVersion As String = "9.0"


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

If Me._site = Nothing Then


Throw New _
System.ComponentModel.Win32Exception(-2147467259)

Shared ToolName As String = "TextGenerator"


Shared ToolDesc As String = _

End If

"Generates a class from text input"


Shared ToolGUID As String = _
" B2429B91-452D-4a95-A355-435337729EFB "

Dim objectPointer As IntPtr = _


System.Runtime.InteropServices.Marshal. _
GetIUnknownForObject(Me._site)

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

22

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Try

0309vsm_F2HowTo_16-23.v7

2/19/09

12:33 PM

Page 23

B U I L D I N G C U S TO M TO O LS

Instantly Search
Terabytes of Text
N dozens of indexed,

System.Runtime.InteropServices.Marshal. _
QueryInterface(objectPointer, riid, ppvSite)
If ppvSite = IntPtr.Zero Then
Throw New _
System.ComponentModel.Win32Exception(-2147467262)
End If
Catch
End Try
End Sub
Public Sub SetSite(ByVal pUnkSite As Object) Implements _
Microsoft.VisualStudio.OLE.Interop. _
IObjectWithSite.SetSite
Me._site = pUnkSite
End Sub

The GetDefaultExtension method provides the extension that VS


will add to the file containing your generated code, so you may need
to change it. This example causes VS to create a file with the format
filename.generated.cs:
Public Function DefaultExtension( _
ByRef pbstrDefaultExtension As _
String) As Integer Implements _
Microsoft.VisualStudio.Shell.Interop. _
IVsSingleFileGenerator.DefaultExtension
pbstrDefaultExtension = ".generator.cs"

unindexed,
fielded data and
full-text search
options (including
Unicode support
for hundreds
of international
languages)
N file parsers /

converters for
hit-highlighted
display of all
popular file
types
N Spider supports

static and
dynamic web
data; highlights
hits while
displaying links,
formatting and
images intact

h Spider
Desktop wit
h Spider
Network wit
CD/DVDs
Publish for
pider
Web with S
Win & .NET
Engine for
Linux
Engine for

New
64-bit

N API supports .NET, C++, Java, databases, etc.

New .NET Spider API

Return 0
End Function

When VS is ready to generate your code, it calls the IVsSingleFileGenerator interfaces Generate method. VS passes the method the
name of the file, the projects namespace, the files contents, and a
progress bar. You must update the methods two ByRef/out
parameters with an array of bytes containing your generated code
and the length of your array. You should set the array parameter to
nothing and the length parameter to 0 if your code generation
fails.
Rather than rewrite the Generate method for every custom
tool, have the Generate method create a class called CodeGenerator
and call a method on it named GenerateCode. Always pass the GenerateCode method the name of the file, the project Namespace, the
file contents and the progress bar that VS passes to the Generate
method. As a result, the Generate method becomes a set of boilerplate code that looks the same in every custom tool:
Dim generatedCode() As Byte
Try
Dim cg As SiteGenerator = New CodeGenerator
generatedCode = cg.GenerateCode(wszInputFilePath, _

The Smart Choice for Text Retrieval


since 1991
N Bottom line: dtSearch manages a terabyte of text

in a single index and returns results in less than a


second InfoWorld
N For combing through large amounts of data,

dtSearch leads the market Network Computing


N dtSearch covers all data sources ... powerful

Web-based engines eWEEK


N dtSearch searches at blazing speeds Computer

Reseller News Test Center


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

Contact dtSearch for


fully-functional evaluations

wszDefaultNamespace, bstrInputFileContents, _
pGenerateProgress)

1-800-IT-FINDS www.dtsearch.com
VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

23

0309vsm_F2HowTo_16-23.v7

2/19/09

1:02 PM

Page 24

B U I L D I N G C U S TO M TO O LS

When youre ready to start generating code, replace the


line in your GenerateCode method that sets the
generatedCode variable with a line that sets the
variable to a string containing your code.
rgbOutputFileContents(0) = _
System.Runtime.InteropServices.Marshal. _
AllocCoTaskMem(generatedCode.Length)
System.Runtime.InteropServices.Marshal.Copy( _
generatedCode, 0, rgbOutputFileContents(0), _
generatedCode.Length)
pcbOutput = generatedCode.Length
Catch
pcbOutput = 0
rgbOutputFileContents(0) = IntPtr.Zero
End Try

Generating Code
Youre now finally ready to start writing the code thats unique
to your code generator. Start with a standard version of your
CodeGenerator class, which writes to the output file the parameters
passed to it from the Generate method. This code lets you check
that 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 = "" Then
Throw New Exception("No content")

Whatever method you choose, you should see a new file added
under your existing file with the file extension you specified in the
GetDefaultExtension method and holding the output from your
GenerateCode method.
Of course, it might not work the first time. Problems usually
are related to registering your custom tool with Windows. If this is
the case, the message youll get will typically say that your custom
tool cannot be found. A number of typical problems can occur.
First, the GUID you used in the GUID attribute on your class
might be different than the Guid you set the ToolGUID variable
to. Second, the two methods that add and remove the keys to the
Windows registry might be wrong. Check that youve got the right
version number for VS and the right GUID for the language
youre testing in. For example, did you create a key for C# but then
test your custom tool in a VB project? Its helpful to open RegEdit
and look at the keys youre generating to see if they look like the
other keys in the Generators section.
Finally, your custom tool might not have gotten into the
GAC. If a problem exists with your PostBuild event, youll see a
message in your Output window. You can also try removing your
custom tool from the GAC by using gacutil u nameofyourproject.
If you get a message stating that your assembly couldnt be found,
then youll know that you have a problem getting your tool into
the GAC.
When youre ready to start generating code, replace the line in
your GenerateCode method that sets the generatedCode variable
with a line that sets the variable to a string containing your code.
This example creates a Hello, World class:

End If
Progress.Progress(0, 100)

generatedCode = "namespace " & Namespc & _

Dim generatedCode As String

"{public class NewClass{public string" & _

generatedCode = "Namespace: " & Namespc & ", " & _

" SayHello(string Name){return ""Hello, "" + Name;}}}";

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


"File contents:" & FileContents
Progress.Progress(100, 100)
Return System.Text.Encoding.UTF8.GetBytes( _

You now have a working custom tool. True, the interesting work is
still left to do: reading your files input and turning it into real code.
But thats also the fun part. VSM

generatedCode)
End Function

You must start a new copy of VS to test your custom tool. After the
new copy starts, create a project, add a file, fill it with some text,
and set the files CustomTool property to the name of your custom
tool. In VS 2008, your custom tool runs as soon as you switch
focus away from the file; in VS 2005, you can run your custom tool
by closing the file. In either version of VS, you can also right-click
on the file in Solution Explorer and select Run custom tool.

24

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Peter Vogel (peter.vogel@phvis.com) is a .NET consultant, author and


instructor living in Goderich, Ontario, Canada.
GO ONLINE
Use this Locator+ code at VisualStudioMagazine.com to go directly to these
related resources.
READ & DOWNLOAD
VS0903PV Read this article.

0309vsm_025

2/19/09

4:47 PM

Page 25

Special Advertising Section

SPOTLIGHT
ON GRAPHICS,
IMAGING AND MAPPING
The following advertising section showcases companies offering solutions
for your graphic, imaging and mapping needs.

VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

25

0309vsm_026

2/19/09

11:37 AM

Page 26

Spotlight on Graphics, Imaging & Mapping

Setting a New Standard in


Geospatial Application Development

t ISC, our mission is to provide you with the best tools


and software you will find for fulfilling your organizations
geospatial visualization and analysis needs. The MapDotNet
product line is a perfect fit for any organization that supports
Microsofts .NET platform and is looking for cost-effective
geospatial 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 the
MapDotNet series with extensive support for Windows
Presentation Foundation (WPF) and Silverlight, as well as
AJAX. With a focus on user experience, MapDotNet UX is
the toolkit for GIS integration with consumer-based
mapping platforms.

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 is
licensed per server, not per processor.
MapDotNet UX SDK: WPF and Silverlight 2.0 controls, a
Virtual Earth tile handler for use in AJAX applications, and
an extensive class library.
MapDotNet is
a product of

www.mapdotnet.com

Interactive Mapping is our Passion


A platform designed to allow you to rapidly visualize,
Setting the standard in geospatial
application development.

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

MapDotNet with
Silverlight Interface

modernized interactive map design on your desktop.

Microsoft recommends MapDotNet when you need to


intergrate existing Geographic Information Systems (GIS)
with Microsoft Virtual Earth .
TM

Download 60 day trial at www.mapdotnet.com


or call us at (850) 893-6741.
Copyright 2009, ISC, all rights reserved.

0309vsm_027

2/19/09

12:46 PM

Page 27

Spotlight on Graphics, Imaging & Mapping


GISBetter Decisions through
Modeling and Mapping Our World
Setting the standard in geospatial application development.

Interactive Mapping
is our Passion
An 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
MapDotNet with
Silverlight Interface

and MapDotNet Server for AJAX.

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. Founded
in 1969, ESRI is the leading developer of GIS software with more
than 300,000 clients worldwide.
Contact us today to learn how ESRIs GIS is helping to manage and
improve business operations around the world.

1-800-447-9778
Download a 60 day trial at www.mapdotnet.com
or call us at (850) 893-6741.
Copyright 2009, ISC, all rights reserved.

info@FTSJDPN t XXXFTSJDPN
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.

The World Leader in Imaging Development SDKs


LEAD Technologies is the
developer and publisher of
LEADTOOLS, the awardwinning line of development
toolkits. The result of 18
years of development, a
LEADTOOLS SDK literally
puts millions of lines of code
at the fingertips of developers.
The LEADTOOLS line helps
programmers integrate color,
document, medical, multimedia,
and vector imaging projects into
their applications quickly and easily, offering development
support for 150+ File Formats, Image Compression,
Image Display, Annotations, Forms Recognition, Document
Clean-Up, PDF and PDF/A, OCR, Barcode, Scanning/
Capture and DICOM.

Founded in 1991, Pegasus Imaging is trusted to deliver


imaging software development kits (SDKs) and tools
featuring superior image viewing, compression, recognition,
and image-editing technologies. The company exceeds
speed and quality requirements for document imaging,
forms processing, medical imaging, DICOM, photo imaging,
video applications and more. Technology is delivered as
Microsoft .NET, ActiveX, and Silverlight controls, WF Activity
Libraries, DLLs and applications. Multiple 32-bit and 64-bit
platforms are supported, including Windows, Windows
Mobile, Java, Java ME (mobile), Linux, Sun Solaris and IBM
AIX. Download full-featured trials and demos today.

www.leadtools.com/vsm2009

www.pegasusimaging.com
VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

27

0309vsm_028

2/19/09

11:45 AM

Page 28

Spotlight on Graphics, Imaging & Mapping

LEAD Technologies, Inc. is the publisher of LEADTOOLS, the world leader in imaging components
for developers. LEADTOOLS SDKs are used by virtually every Fortune 1000 company, including
Microsoft, 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 eliminate
months of research and development, and add high levels of quality, performance and functionality.
Key Features and Benets

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.
Efciently store and transmit images with the industrys 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.
Barcode

Document Clean-up

Form Recognition

Document Imaging Engine


Load and save over 150 different formats including PDF/A and XPS. Add specialized bitonal image
processing, viewing, high speed scanning, annotations, and document image compression to your
business applications. Includes a powerful document clean-up engine to despeckle, deskew, remove
lines, borders, hole-punches and inverted text and make other corrections. Display features include
fast view port rotation for instant rendering and optimized scale to gray and favor black. Maximize
scanner performance with auto-detection of the fastest settings for image acquisition from TWAIN 2.0
and WIA devices. Mark-up images with the industrys most comprehensive and highly customizable
annotation engine including notes, pointers, redactions, highlights, stamps, measurement tools and
audio/video. Save disk space and network bandwidth with LEADs advanced bitonal image compression
algorithms 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 and
write a wide variety of linear and 2D barcode symbols.
Medical Imaging Engine
Develop state-of-the-art imaging applications for use by the healthcare industry with high and low
level DICOM data manipulation and secure DICOM communication. A customizable display container
features built in viewing tools. Extend PACS access to the Internet, including web based reading and
consulting with HTML or rich clients and web services. Support for extended grayscale and color image
processing and compression such as JPEG, JPEG 2000 and MPEG-2. LEADTOOLS provides high level
support for waveforms, printing, digital signatures, overlays, softcopy presentation, modality LUT,
VOI, LUT and DICOM annotations and graphics objects. Includes sample source code for DICOM server
and client services to query, retrieve, store and Modality Worklist.
Imaging Engine
Incorporate digital imaging functionality into your applications. Load, save and convert over 150 formats
including TIFF, EXIF, PDF and PSD supporting a wide range of color spaces and compression types
including JPEG, JPEG XR, JPEG 2000, CCITT G3/G4, LZW and ZIPLIB. Easily capture from screen and any
32/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 with
built-in features such as pan, zoom and magnify, thumbnail browser and imaging common dialogs.

Annotations

Multimedia Imaging Engine


Enable your Windows and Web applications with multimedia capture, playback, conversion and
editing. 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 other
le types. Add support for portable devices including iPhone/iPod, PSP, ZEN, Zune, SmartPhone and
others. Encode, decode and transcode with LEADs optimized software codecs including H264, MPEG4,
H263, and MPEG-2 or any third party codecs. LEAD multiplexers and demultiplexers such as MPEG-2
Program and Transport, MP4, OGG and FLV are available.

LEADTOOLS SDKs feature LEADs iCompress Technologies.


Free 60 Day Evaluation! www.leadtools.com/vsm
866 530-3399

28

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Project5

2/6/09

8:48 AM

Page 1

LEADTOOLS v.16 .NET, WPF, WCF,


WF, C API, C++ Class Lib, COM & more!
Document

Barcode

Form Recognition & Processing

Mark-up

DICOM Medical

Multimedia

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 of
quality, 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 LEADs
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: Automatically identify forms and extract user filled data.
Document Cleanup/Preprocessing: Deskew,
despeckle, line and border removal, registration
marks and more.
PDF and PDF/A: Read/write raster and text
searchable PDF files.
Annotations: Interactive UI for document
mark-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.

LEADTOOLS SDKs feature LEADs iCompress Technologies.


Free 60 Day Evaluation!
www.leadtools.com/vsm
866 530-3399

0309vsm_030

2/19/09

11:53 AM

Page 30

Spotlight on Graphics, Imaging & Mapping

Pegasus Imaging: Your Single Source


for Imaging SDKs

he year 2008 ended


with an acquisition that
shook up the imaging
marketplace, shocking
competitors and
pleasantly surprising many industry
analysts, vendors, OEMs and
individual enterprises. Pegasus
Imaging and AccuSofts imaging
businesses combined to become
one imaging technology powerhouse. Three weeks later, the
industry saw them acquire a third
vendor Tasman Software. Today,
the new company is uniquely
positioned to be the largest and
most experienced provider of imaging software development
kits (SDKs) and image-viewing solutions in the world.

With decades of experience behind them, the companies


have joined together to merge solid product lines,
extraordinary talent and an incredible amount of intellectual
property. Pegasus Imaging is expanding to create an
unbeatable 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 are
used in various development environments and on multiple
platforms. Find SDKs for .NET, ActiveX, Silverlight,
ASP.NET, WF activities (that can be used with Microsoft
SharePoint), 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 offering
their own individual set of benefits.

ImagXpress and ImageGear are the flagship imaging SDKs


to 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 and
assist in process automation efforts. The FormSuite SDK
bundles industry-leading forms processing, form recognition,
form dropout, image cleanup and editing, zonal OCR, ICR
and OMR. PDF Xpress offers advanced PDF support, and
OCR Xpress adds full-page text recognition. Thousands of
software engineers rely on these products. Download and
discover the many advantages of being a Pegasus customer.
Pegasus Imaging is committed to delivering superior
technical support and customer service by trained, in-house
teams dedicated to help meet customer needs. Products
are offered as full-featured trials prior to licensing. Pegasus
Imaging is a leader in research and development of imaging
technologies, and is the provider of choice for developers of
document imaging, health-care imaging and photo/video
imaging solutions worldwide.

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

www.pegasusimaging.com
30

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

Project2

2/9/09

11:57 AM

Page 1

0309vsm_C#Corner_32-35.v7

2/19/09

C# CORNER

12:45 PM

Page 32

ANONYMOUS TYPES

Create Anonymous
Types
Taking 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 typesincluding
whether they are classes
or structs.
BY BILL WAGNER

# developers create types every day. But how often do developers think about how well
their types behave with the type system? Do they write the methods and define the behavior their users will expect one day? What capabilities will the .NET Framework expect
from any type?
Answering these questions isnt much work, but its probably a bit more than you do today. Taking
a look at the capabilities the compiler gives to anonymous types also serves as an excellent tutorial on
what 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 in
the sequence of those objects (see Go Online, p. 35, to access a sample listing). The program isnt that interesting in itself, but its instructive to look at the code the compiler generates for that anonymous type.
Now its 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 for
anonymous types to avoid collisions with user-created names. Also, the compiler creates a generic class,
which it uses for some other optimizations.
Lets 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 is
public, you should change that habit. How many classes do you create that will never be accessed outside
of the current assembly? Are those public? If so, youre creating public classes unnecessarily, and youre
adding names to your public API that arent necessary. That creates more confusion for your users. They
arent 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

32

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

ILLUSTRATION FROM ISTOCKPHOTO.COM

0309vsm_C#Corner_32-35.v7

2/19/09

12:45 PM

Page 33

C# CORNER ANONYMOUS TYPES

API docs. This essentially pollutes your users experience with your
application. You should always choose the least-visible access to
achieve your goal.
Anonymous types are sealed. This is an obvious choice
because you cant derive a new type from something you cant
name. Your job is somewhat more difficult. You need to examine
your types and make an explicit decision to support or deny
derived classes from your type. If you believe developers shouldnt
extend your type, make that statement explicit by using the sealed
keyword. If you believe developers will want to extend your type,
pay careful consideration to where derived types will want to
extend or change the behavior of your type. Make those methods
virtual and provide explicit guidance on the extension points
youve created. You should always support or prohibit derivation
explicitly; dont leave it to client developer interpretation.
Check the Anonymous Type
Next, you should check whether the anonymous type is immutable.
(VB.NET supports both mutable and immutable anonymous
types.) Immutable types are simpler for many reasons: You can validate state in constructors and know theyre always valid; immutable
types can be shared safely across threads; and immutable types simplify testing because state changes cant affect later methods. However, its overly simplistic to say that every type in your programs
should be immutable; thats simply not practical.You should prefer
immutable types whenever possible. When design issues force you
to create mutable types, you should understand that those types are
more complicated, will introduce more errors and will introduce
more complications in testing. The more related data fields in a
type, the more complicated the relationships are.
There are three methods added to every anonymous type by
the C# compiler: overrides of Object.ToString(), Object.Equals()
and Object.GetHashCode(). Object.ToString() helps in even this
small sample. You can print the anonymous type object instead of
writing extra code to print each of the fields from the anonymous
type. Over the course of a larger application, a proper ToString()
method makes it easier to use your type any time you want to display
the information in an object for your users, or even in the debugger
for other developers.You should always create a ToString() method
that 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 reference semantics. That means two objects are equal if they contain
the same information, rather than if they refer to the same object. If
you modify Equals(), you do need to create a corresponding GetHashCode() to ensure that objects that are equal always return the
same hash value. When you create your own types, you can choose
to follow either reference semantics or value semantics. In general,
types that are primarily data-storage types should follow value
semantics. Types that are primarily defined by their behavior
should follow reference semantics. Once again, make that an
explicit decision: Determine which makes more sense for your
type, and implement that appropriately.

Critique on Anonymous Types


Of course, nothing is perfect, including the implementation of
anonymous types by the C# compiler. When you create your own
types, you should consider additional decisions as part of every type
you create. The first of these is related to equality semantics. The
Object.Equals() override uses the ultimate base class, System.Object.
As of .NET 2.0, you have a generic interface for equality: IEquatable<T>.Anytime you override System.Object.Equals(), you should
implement IEquatable<T> for your type. For example, you should
add 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 the


System.Object override. Notice that you can now defer the implementation of System.Object.Equals to your strongly typed version:
#region IEquatable<AnonymousTwo> Members
public bool Equals(HandCodedPoint other)
{
return (((other != null) &&
EqualityComparer<int>.Default.Equals(
this.xField, other.xField)) &&
EqualityComparer<int>.Default.Equals(
this.yField, other.yField));
}
#endregion
public override bool Equals(object value)
{
return Equals(value as HandCodedPoint);
}

If youve created your own version of Equals() and implemented


IEquatable<T>, you should create your own operator == and
operator !=. Because youve already written the logic in your
IEquatable<T> method, you can reuse that implementation in
your 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 34

C# CORNER ANONYMOUS TYPES

The lesson to take away from these examples: Equals touches many
methods; make sure theyre all consistent.
You should also consider implementing IComparable<T>
(and the non-generic IComparable) if your type has an obvious
ordering 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 +

New 7.0
e
mag
DotI ease
Rel

other.yField + other.yField;
return distanceSquared.CompareTo(
otherDistanceSquared);
}
public int CompareTo(object obj)
{
return CompareTo(
obj as HandCodedPoint);
}

Implementing IComparable implies you


have also defined operator > and operator
<. Youve already written the algorithm, so
all you need to do is add the signature and
call the methods youve already written:
public static bool operator >(

The .NExT Step In Document


and Photo Imaging

HandCodedPoint
left, HandCodedPoint right)
{
if (left == null)
return false;
else

DotImage 7.0More Powerful,


with Zero-Footprint Imaging, and
3 Months of Free Gold Support.

return left.CompareTo(right) > 0;


}
public static bool operator <(
HandCodedPoint
left, HandCodedPoint right)

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


support, AJAX Vector Annotations including FreeHand, WPF annotations, and more. Use templates in our AJAX Wizard to create zerofootprint web applications in C# and VB.NETTake document and
photographic imaging to the .NExT step.

{
if (left == null)
return right != null;
else
return left.CompareTo(right) < 0;
}

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

Atalasoft, Your .NET Imaging Partner


Call us toll free at 866-568-0129

HandCodedPoint implements both IComparable<T> and IEquatable<T>, so you


should add the operators >= and <=:

www.atalasoft.com

public static bool operator >=(


HandCodedPoint

34

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

0309vsm_C#Corner_32-35.v7

2/19/09

12:45 PM

Page 35

C# CORNER ANONYMOUS TYPES

left, HandCodedPoint right)


{
return (left == right) || (left > right);
}

spend some time thinking of the basic behavior thats expected of


your types, and create that behavior for your users. Rather than just
ignoring the basic behavior, decide which behavior should be
implemented in your type and create it. VSM

public static bool operator <=(HandCodedPoint


left, HandCodedPoint right)
{
return (left == right) || (left < right);
}

This is a fair amount of work and I dont recommend adding it to


every single type you create. However, you should give it some
thought and make sure you know when you should and shouldnt
care about certain behaviors. Obviously it doesnt make any sense
to define an ordering relation between windows or many other
types you create.
Anonymous types include a fair amount of code to implement the behavior that you would expect on every type.You should
follow the same guidelines and create methods that all your users
will expect or implement in their own version. You should also

C#

Bill Wagner, author of Effective C#: 50 Specific Ways to Improve


Your C# (Addison-Wesley Professional, 2004) and More Effective
C#: 50 Specific Ways to Improve Your C# (Addison-Wesley Professional, 2008), has been a commercial software developer for the past
20 years. He is a Microsoft Regional Director and a Visual C# MVP.
His interests include the C# language, .NET Framework and software design. E-mail Bill at wwagner@srtsolutions.com.
GO ONLINE
Use these Locator+ codes at VisualStudioMagazine.com to go directly to
these related resources.
READ & DOWNLOAD
VS0903CC Read this article and download the sample code online.

REPRESENTATION OF AN ANONYMOUS TYPE

internal sealed class AnonymousOne


{
// Fields
private readonly int xField;
private readonly int yField;
// Methods
public AnonymousOne(int x, int y)
{
this.xField = x;
this.yField = y;
}

(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();
}

public override bool Equals(object value)


{
var type = value as AnonymousOne;
return (((type != null) &&
EqualityComparer<int>.Default.Equals(this.xField,
type.xField)) &&

// Properties
public int x
{
get { return this.xField; }
}

EqualityComparer<int>.Default.Equals(this.yField,
type.yField));
}
public override int GetHashCode()
{
uint num = 0xdd9cb371;
num = (0xa5555529 * num) +

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 reuse
some code. Also, the compiler generates names that are illegal for handwritten code to avoid collisions with user-defined types.

VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

35

0309vsm_AskKat.36-38.v6

Ask

2/19/09

1:27 PM

Page 36

Kathleen

DISPLAY MULTIPLE
PAGES IN SILVERLIGHT

BY KATHLEEN DOLLARD

Learn how to display multiple pages in Silverlight and discover the tools
and controls that ship with it; track down a bug in a case statement; and
take advantage of helpful tips for trying to obtain a clean Code Analysis.
Technologies mentioned in this article include
Silverlight, Windows Presentation Foundation,
Visual Studio Team System, Visual Basic and C#.

Q
A

How can I change forms in Silverlight so my application


works in exactly the same way in both my Silverlight
and WinForms applications?

Silverlight Forms correspond roughly to Pages in Silverlight, and each Silverlight application has exactly
one Page. So, Id like to rephrase your question to
something like this: How can I make it seem as though Im
changing forms? Once you ask the question this way, youre
halfway to the answer.You provide a page that acts as a container
for user controls, and each user control corresponds to a form in
your existing application (see Figure 1). Pages can have only one
content element, so you generally use a container such as a grid
to hold your user controls. The grid is a nice container to use
because it lets you overlay controls when needed; it also lets you
include features that behave consistently across all your user
controls. This is similar to using a Master Page in ASP.NET.

Ive heard theres a TreeView control for Silverlight 2.0,


but I dont see it in the toolbox. Im having a hard time
figuring out what controls are in Windows Presentation
Foundation [WPF] and Silverlight, respectively.

Microsoft is releasing controls for both WPF and


Silverlight as Toolkits. This avoids delaying the
release of important tools until a normal ship cycle.
In addition to the controls it ships with, Silverlight has a
preview of a Visual State Manager in the main tool, while WPF
has a preview in the WPF Toolkit. The Silverlight Toolkit also
includes a preview of an Implicit Style Manager that recreates
some functionality thats inherently part of WPF.

36

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

The Visual State Manager in Silverlight allows you to


describe states for controls, and defaults for what the controls
should look like when theyre in each state. It also allows you
to dictate how long the transition into a given visual look
should take (the length of the animation). When creating
applications, programmers can override the standard state
appearance with their own. The Blend tooling for this is
extremely good, making it much easier to customize controls
than in WPF, where individual styles and triggers are needed
to provide this functionality.
The Implicit Style Manager introduced to Silverlight as
a preview in the Silverlight Toolkit allows you to apply the
style based on type, rather than by requiring an explicit style
declaration on each instance of each control. This isnt as
automatic as the WPF approach because each control is
based on a container that applies styles as a theme, and the
container must be placed in each user control. Also, you cant
change the theme at runtime. The good news is that the
Silverlight Toolkit contains a great set of themes to get
you started.

I have a bug in a case statement that I dont understand.


This code works correctly when the direction is right or
below. It throws an InvalidOperationException when
None (the default) is passed, which it shouldnt do. Direction is
an enum. Can you tell me whats wrong?

Select Case mDirection


Case Direction.Right
location = New Point(mPopup.ActualWidth, 0)
Case Direction.Below Or Direction.None
location = New Point(0, -mPopup.ActualHeight)
Case Else
Throw New InvalidOperationException()
End Select

0309vsm_AskKat.36-38.v6

2/19/09

1:47 PM

Page 37

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

This is an easy mistake to make because Or acts


as a bitwise or Boolean operator depending on
the operands. In this case, the operands for
the Or operator in the line Ive highlighted act as a
bitwise operator. Im going to guess that the value of
Directions.None is zero, which is a good choice for the
default value. If thats true, the result of the Or operation
is Direction.Below. This is why it works for everything
except the value of Direction.None.
Just use a comma to separate the different values
you wish to match:

Case Direction.Below, Direction.None

If you make this mistake in C#, you fix it by using two


adjacent 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;

FIGURE 1 Display Several Silverlight Forms Simultaneously. Silverlight


runs in a browser, so theres only one Page that serves as the RootVisual or visual
entry point for your application. You cant change the RootVisual as your application
runs. 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 that
contain the forms of your application. The Page might be empty or contain visual
elements common to all of your user controls.

Im trying to get a clean Code Analysis. Unfortunately, the


code 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)

Code Analysis analyzes the Release Assembly. The


compiler removes the Diagnostics.Debug line when compiling. If you check the IL through Reflector, youll see that
the only code using the parameter and variable doesnt exist within
the Release Assembly. Interestingly, the same code in VB gives a second warning:

{
string text = String.Empty;

CA1804 : Microsoft.Performance : 'MenuProvider.WriteMes-

if (mOwner.Content != null)

sage(String)' declares a variable, 'text', of type

'String', which is never used or is only assigned to. Use


text = mOwner.Content.ToString();

this variable or remove it.

}
System.Diagnostics.Debug.WriteLine(
text + ":" + message);
}

The warning is:


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

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

There are a few ways to work around these problems, but your boss
is making a mistake when he insists on setting a goal for full Code
Analysis compliance without suppressing any items. A good solution in this case is to formally ignore the warnings. If you rightclick on the warning, youll have the option of ignoring it in an
external file or in the source code. I much prefer suppressing the
messages in source code and always including a Justification. This
lets other coders know why you decided to ignore the warning.
You cant just remove the code with conditional compilation
because other code is calling the method. A slightly more complex
approach would be to alter the class to be a partial class and add a
new declaration for a partial method with the same signature
VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

37

0309vsm_AskKat.36-38.v6

2/19/09

1:27 PM

Page 38

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

You cant just remove the code with conditional


compliation because other code is calling the method.
(name and parameters) as your WriteMessage method. You dont
need a second class declaration; instead, change the existing one to
include the keyword partial. Then wrap your actual WriteMessage
method entirely in a #if DEBUG directive:
partial void WriteMessage(string message);
#if DEBUG

Prior to the introduction of generics in .NET 2.0 (VS


2005), each unique event with a unique set of parameters
needed an explicit declaration of a delegate that corresponded to the event signature. By convention, these events were
named with the name of the event followed by EventHandler. If
you checked the code in Reflectorwhich is still free, but now distributed by Red Gate Software Ltd.youd see a delegate within the
class that was generated by the compiler:

partial void WriteMessage(string message)


{

Public Delegate Sub _


// Code as above

ByVal sender As Object, _

#endif

ByVal e As MenuItemClickEventArgs)

When you compile this code for debugging, Visual Studio will find
the real WriteMessage method, and the method will work as
expected. When you compile for release, the DEBUG constant will
be missing, so your implementation of WriteMessage will be missing. Due to the partial class declaration, the compiler will remove
all calls to your WriteMessage method.
This only works because your method is private and void. It also
provides a slight runtime performance improvement because calls
wont be made to the method, and the string concatenation wont be
performed.This performance improvement will be small,but can still
prove significant if you call this method a number of times.

MenuItemClickEventHandler( _

Im trying to get a clean Code Analysis run for some Visual


Basic code, but Im getting the following warnings:

Warning 3 CA1034 : Microsoft.Design : Do not nest type 'MenuItem.MenuItemClick2EventHandler'. Alternatively, change its
accessibility so that it is not externally visible.
SilverlightMenuLibrary
Warning 4 CA1003 : Microsoft.Design : Visual Basic generates

Code Analysis is warning you that theres a nested delegate. This


was appropriate for the generated delegate because it limited the
potential for naming collisions. If youd like to quiet the errors, you
can 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
shouldnt ignore it and that its a breaking change. This warning
holds true for C#, but not for VB. The only downside of this style of
event declaration is a few extra lines of code of IL in the assembly,
which hardly justifies saying you should never suppress the warning. The automatic usage means changing it isnt a breaking
change. You can suppress the second message globally and just
ignore warnings about event handlers, but you cant suppress the
first globally without missing notification on any other nested public classes. I think its easier to change your delegate declarations
than to explain why youre sticking with the old VB style and managing the suppressions. VSM

EventHandler delegates for events that use the following


pattern: Event MyEvent(ByVal Sender As Object, ByVal e as
MyEventArgs). Change the event that defines EventHandler
'MenuItem.MenuItemClick2EventHandler' to use
EventHandler<T> by defining the event type explicitly, e.g.
Event MyEvent As EventHandler(Of MyEventArgs).

Kathleen Dollard (kathleen@mvps.org) is a consultant, author, trainer


and speaker. Shes been a Microsoft MVP for 10 years and is an active
member of the INETA Speakers Bureau. She wrote Code Generation in
Microsoft .NET (Apress, 2004), is the founder and principal of GenDotNet and blogs at http://msmvps.com/blogs/kathleen.

SilverlightMenuLibrary
GO ONLINE

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?

38

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

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


related resources.
READ MORE
VS0903AK Read this article online.

0309vsm_AdIndex_39

2/19/09

3:44 PM

Page 39

Advertising Sales

Ad Index
Advertiser

Page

Atalasoft, Inc
www.atalasoft.com
ComponentOne
www.componentone.com

East
Andrew Mintz
National Sales Manager
Phone: 508-532-1433
amintz@1105media.com

Microsoft Account Manager


Danna Vedder
Phone: 253-514-8015
dvedder@1105media.com

Copyright Statement
Copyright 2009 by 1105 Media, Inc. All rights reserved.
Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to
"Permissions Editor," c/o Visual Studio Magazine, 2600 El
Camino Real, Ste 300, San Mateo, CA 94403.

Legal Disclaimer
The information in this magazine has not undergone any
formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied. Implementation or
use of any information contained herein is the reader's sole
responsibility. While the information has been reviewed for

5, 27

Intel Corporation
www.intel.com
LEAD Technologies, Inc.
www.leadtools.com

Director, Print Production


Jenny Hernandez-Asandas
Phone: 818-734-1520 ext 101
Fax: 818-734-1528
jhernandez@1105media.com

Production Coordinator

Serena Barnes
Phone: 818-734-1520 ext 164
vsmadproduction@1105media.com
sbarnes@1105media.com

ID Statement
Visual Studio Magazine (ISSN 1537-002X) is published
monthly by 1105 Media, Inc., 9121 Oakdale Avenue, Ste. 101,
Chatsworth, CA 91311. Periodicals postage paid at
Chatsworth, CA 91311-9998, and at additional mailing
offices. Complimentary subscriptions are sent to qualifying
subscribers. Annual subscription rates for non-qualified subscribers are: U.S. $34.97, Canada $52.97 (U.S. funds);
International $78.97 (U.S. funds). Subscription inquiries,
back issue requests, and address changes: Mail to: Visual
Studio Magazine, P.O. Box 1164, Skokie, IL 60076-8164,
email VSM@1105service.com or call toll free (888) 7688759, fax number 847-763-9564. International calls 847763-9135. POSTMASTER: Send address changes to Visual
Studio Magazine, P.O. Box 1164, Skokie, IL 60076-8164.
Canada Publications Mail Agreement No: 40612608. Return
Undeliverable Canadian Addresses to Circulation Dept. or
Bleuchip International, P.O. Box 25542, London, ON N6C 6B2.

23

ESRI
www.esri.com

West

William Smith
Phone: 603-886-3466
wsmith@1105media.com

dtSearch Corp.
www.dtsearch.com

Chris Kourtoglou
Regional Sales Manager
Phone: 650-579-0121
ckourtoglou@1105media.com

National Accounts Director

34

accuracy, there is no guarantee that the same or similar


results may be achieved in all environments. Technical inaccuracies may result from printing errors and/or new developments in the industry.

Corporate Address
Corporate Headquarters:
1105 Media
9121 Oakdale Ave. Ste 101, Chatsworth, CA 91311
www.1105media.com

Media Kits
Media Kits: Direct your Media Kit requests to Matt Morollo,
VP Publishing, 508-532-1418 (phone), 508-875-6622
(fax), mmorollo@1105media.com

Reprints
Reprints: For single article reprints (in minimum quantities of
250-500), e-prints, plaques and posters contact:
PARS International
Phone: 212-221-9595
E-mail: 1105reprints@parsintl.com
www.magreprints.com/QuickQuote.asp

List Rental
This publications subscriber list, as well as other lists from
1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone:
914-368-1000; E-mail: 1105media@meritdirect.com;
Web: www.meritdirect.com.

C4
27, 28, 29

MapDotNet
www.mapdotnet.com

26, 27

Microsoft Corporation
www.microsoft.com

C2,1,15

Pegasus Imaging Corporation 27, 30, 31


www.pegasusimaging.com
Rally Software
www.rally.com

16

Red Gate Software


www.red-gate.com
Software FX, Inc.
www.softwarefx.com
Tallcomponents BV
www.tallcomponents.com

9
20, 21
C3

Wayside Technology Group, Inc


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

2
17

Edit Ad Index
Altova
www.altova.com

11

ComponentOne LLC
www.componentone.com

14

Coverity Inc.
www.coverity.com

10

Infragistics Inc.
www.infragistics.com

10

U2U
www.u2u.be

14, 16

Go to
VisualStudioMagazine.com
to access the stories in this
issue, plus read exclusive
online-only content.

VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE

39

0309vsm_PragDev_40.v2

2/19/09

2:07 PM

The Pragmatic

Page 40

Developer

THE ART OF THE


INTERVIEW

BY BILLY HOLLIS

Whether youre looking for work or looking to hire, one thing you cant
afford to overlook is the importance of a strong interview. This is
particularly true in development, where technical interviews
impose unique demands. Here are a few tips for people on
both sides of the interviewing table.
For Interviewees
The most underused answer in technical interviews is,
I dont know. No one knows all the details on todays platforms. Feeling around for the correct answer to a technical
question makes you look bad.
Dont pad your resume with long lists of technologies
that you supposedly know. Just because a technology was used
at your company and you got within 10 feet of it doesnt mean
you know it or should tout it on your resume.
Bring some sample code, even if the interviewer doesnt
ask for it. About five or six printed pages will do, and it need
not be a complete program or module. This will impress the
people you most want to impress. If the interviewer doesnt
want to see it, that tells you something, too.
Stress the business value of your past contributions to a
company. Most interviewers are a hybrid of business-oriented
and technically oriented. If you have that same balance, it will
make you stand out. If you cant articulate the business value of
your contributions, you need to take stock of yourself. There are
two main possibilities: you simply dont care about the business
side, or your contributions arent really very valuable.
For Interviewers
Dont wing it. If youre doing any significant amount of
interviewing, you owe it to your company to have a list of questions you can ask, so that you dont have to think them up on the
fly. I have a list of about 40 questions that I mix and match,
depending on how the interview goes. (No, you cant have it.)
Ask a combination of technical and soft skillquestions.
You need to gauge technical competence, but non-technical
skills such as teamwork, attitude, process knowledge and so
forth are at least as important. For example: Suppose a project
sponsor lays out a project to you,and you have loosely estimated
that it will take at least six months to do it.Then the sponsor says,

40

VISUAL STUDIO MAGAZINE March 2009 VisualStudioMagazine.com

And weve promised it to the customer in two months.What


do you do? As Captain Kirk says about the Kobayashi Maru test,
theres no ideal answer. Its a test of character.
Ask for sample code. Stress that it need not be a complete project, and that you only need to see a few pages. I
believe that reading that code will tell you more about a candidate than any resume they can write. Occasionally, someone
will reply that all of their code is proprietary and they cant
give you any. You can decide if thats a dodge, but its a clear
signal that the candidate doesnt do any serious professional
development outside of work.
Dont give the candidate a lot of feedback while theyre
answering questions, especially soft-skill questions. Some
candidates will attempt to feel their way into the answer that
you want. Keep your body language neutral while candidates
answer soft-skill questions. If they start going back and forth
between possible answers, floundering for a response I find
acceptable, I scratch them from the list.
Youll have many candidates who will be washouts in
the first five minutes. Dont become abrupt or careless about
your treatment of those candidates. It can hurt your organizations reputation among other developers.
When youre finished asking questions,give the candidate
a chance to ask any questions of you. That includes asking you
why you asked about certain things. They may have been
coached to ask generic questions about the company, but what
youre hoping for are deeper questions that reveal general
inquisitiveness.
Again,these tips focus on technical interviews.You can find
lists of generic interview tips at sites such as interviewtips.org,
and I recommend that you also check those out. VSM
Billy Hollis (billyhollis@gmail.com) is an author, consultant and
veteran software developer on Microsoft technologies. Hes
currently developing Software as a Service applications with
Windows Presentation Foundation and Silverlight and training
others on those technologies. Hollis also speaks regularly at
VSLive! events.

Project3

1/21/09

11:34 AM

Page 1

Project2

2/9/09

11:49 AM

Page 1

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 todays serial apps and tomorrows 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.

Вам также может понравиться